首页 > 解决方案 > 如何使用承诺的节点 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');
};

标签: node.jsbashjarpipechild-process

解决方案


子进程 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 上相同。


推荐阅读