【问题标题】:Use child_process#spawn with a generic string将 child_process#spawn 与通用字符串一起使用
【发布时间】:2016-12-28 13:58:24
【问题描述】:

我有一个字符串形式的脚本,我想在 Node.js 子进程中执行。

数据如下:

const script = {
    str: 'cd bar && fee fi fo fum',
    interpreter: 'zsh'
};

通常情况下,我可以使用

const exec = [script.str,'|',script.interpreter].join(' ');

const cp = require('child_process');
cp.exec(exec, function(err,stdout,sterr){});

但是,cp.exec 缓冲 stdout/stderr,我希望能够将 stdout/stderr 流式传输到任何地方。

有谁知道是否有办法以某种方式将cp.spawngeneric 字符串一起使用,就像您可以使用cp.exec 一样?我想避免将字符串写入临时文件,然后使用 cp.spawn 执行该文件。

cp.spawn 将与字符串一起使用,但前提是它具有可预测的格式 - 这是针对库的,因此它需要非常通用。

...我只是想到了一些事情,我猜最好的方法是:

const n = cp.spawn(script.interpreter);
n.stdin.write(script.str);   // <<< key part

n.stdout.setEncoding('utf8');

n.stdout.pipe(fs.createWriteStream('./wherever'));

我会尝试一下,但也许有人有更好的主意。

downvoter:你没用

【问题讨论】:

  • omg 荒谬的反对票,谢谢

标签: node.js bash zsh child-process


【解决方案1】:

好的,想通了。

我使用了这个问题的答案: Nodejs Child Process: write to stdin from an already initialised process

以下允许您使用不同的 shell 解释器将通用字符串提供给子进程,以下使用 zsh,但您可以使用 bashsh 或任何真正的可执行文件。

const cp = require('child_process');

const n = cp.spawn('zsh');

n.stdin.setEncoding('utf8');
n.stdin.write('echo "bar"\n');   // <<< key part, you must use newline char

n.stdout.setEncoding('utf8');

n.stdout.on('data', function(d){
    console.log('data => ', d);
});

使用Node.js,也差不多,不过好像需要多用一个调用,也就是n.stdin.end(),像这样:

const cp = require('child_process');

const n = cp.spawn('node').on('error', function(e){
    console.error(e.stack || e);
});

n.stdin.setEncoding('utf-8');
n.stdin.write("\n console.log(require('util').inspect({zim:'zam'}));\n\n");   // <<< key part

n.stdin.end();   /// seems necessary to call .end()

n.stdout.setEncoding('utf8');

n.stdout.on('data', function(d){
    console.log('data => ', d);
});

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2023-01-25
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 2016-09-21
    • 2016-04-24
    • 1970-01-01
    相关资源
    最近更新 更多