我正在使用 Node 执行一个 jar 文件,该文件通常采用 CSV 文件作为输入路径。
如果可能的话,我想尝试绕过写入 CSV 文件并将 CSV 作为字符串通过管道传输到进程中。
我可以使用 execSync
进行此操作,但我宁愿使用用 promisify
包装的 exec
问题是 exec
没有像 execSync
这样的 input
选项,因此我无法将数据通过管道传输到其中。你如何解决这个问题?或者将 execSync
包装在 Promise
中是最佳实践吗?
import {execSync} from 'child_process';
export const runJar = async (input: string, cwd: string) => {
const out = execSync(`java -jar model.jar`, {
cwd,
input,
})
return out.toString('utf-8');
};
最佳答案
子进程 stdio 的简约示例用法。
const child_process = require("child_process");
const fs = require("fs");
// exec returns a child process instance
// https://nodejs.org/dist/latest-v14.x/docs/api/child_process.html#child_process_class_childprocess
const child = child_process.exec("cat");
// write to child process stdin
child.stdin.write("Hello World");
// to read/parse your csv file
//fs.createReadStream("./file.csv").pipe(child.stdin);
// listen on child process stdout
child.stdout.on("data", (chunk) => {
console.log(chunk);
child.kill();
});
要实现这一点,您可以监听子进程的退出(状态),并根据退出代码解决或拒绝 promise :
child.on("close", (code) => {
if (code != 0) {
reject();
} else {
resolve();
}
});
给出的例子:
const readParseCSV = function (file = "./file.csv") {
return new Promise((resolve, reject) => {
const child = child_process.exec("java -jar model.jar");
fs.createReadStream(file).pipe(child.stdin);
let response = "";
// listen on child process stdout
child.stdout.on("data", (chunk) => {
response += chunk;
});
child.on("close", (code) => {
if (code != 0) {
reject();
} else {
resolve(response);
}
});
});
};
我不确定这在 Windows 上的工作方式是否与在 Linux 上的工作方式相同。
关于node.js - 如何使用 Promisified Node exec 将文本通过管道传输到命令中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64920341/