node.js - 如何使用承诺的节点 exec 将文本传送到命令中
问题描述
我正在使用节点执行一个 jar 文件,该文件通常将 CSV 文件作为输入路径。
如果可能,我想尝试避免将 CSV 文件和 CSV 中的管道作为字符串写入进程。
我有这个工作,execSync
但我更愿意使用exec
包装的promisify
问题是它exec
没有input
像这样的选项,execSync
所以我无法将数据输入其中。你如何解决这个问题?或者是包装的最佳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();
});
为了保证这一点,您可以监听子进程的退出(状态)并根据退出代码解决或拒绝承诺:
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 上相同。
推荐阅读
- python - 在 Python 中实现 R 模型
- python - 获取机器人发送的所有消息
- mysql - 无法启动 MySQL 社区服务器
- unity3d - 复制文件失败 - UnityEngine.Purchasing.dll
- python - 如何在不传递参数'self'的情况下在python中获取父对象引用?
- javascript - 如何从几个类似的 html 事件中调用一个 javascript 函数
- sql - 从 SQL 存储过程返回默认值作为整数
- android - findViewById 用于返回 null 的多个 TextField
- python - 如何在python中去除日期时间
- python - pytube urllib.error.HTTPError:HTTP 错误 403:禁止