进程替换 - Node.js child_process

问题描述 投票:4回答:4

我正在尝试运行子进程来修改文件(分两步),然后再从stdout读取修改后的内容。我试图通过使用进程替换来做到这一点,它在bash中完美运行,但是当我从节点尝试时却没有。

这是什么,命令看起来像..

var p = exec('command2 <(capture /dev/stdout | command1 -i file -) -',
function (error, stdout, stderr) {
   console.log(stderr);
});

stderr打印:

/bin/sh: -c: line 0: syntax error near unexpected token `('

在节点中执行此操作的正确方法是什么?

node.js bash pipe child-process process-substitution
4个回答
3
投票

我通过将命令放在shell脚本中并从节点子进程调用脚本来解决这个问题。我还需要添加以下内容以在posix模式下设置bash以允许进程替换:

set +o posix

可能有更好的方法直接从节点内执行此操作,但它完成了这项工作。干杯!


1
投票

您可以通过使用spawn标志调用child_process命令,在Node中使用bash替换来sh -c

sh命令使用你的默认bash解释器,-c标志要求解释器从字符串中读取命令,即:$(echo $PATH)。然后将其他标志传递给它们的正常位置参考,例如:$0$1等。

所以一个例子可能是:

const spawn = require('child_process').spawn;

const prg = 'sh',

    args = [
        '-c',
        'echo $($0 $1)',
        'ls', // $0
        '-la' // $1
    ],

    opts = {
        stdio: 'inherit'
    };

// Print a directory listing, Eg: 'ls -la'
const child = spawn(prg, args, opts);

0
投票

你可以让bash用bash -c 'command'评估一个命令。我测试了这个,它适用于进程替换和child_process。


0
投票

这是由调用/bin/sh时以posix模式运行的bash引起的。

直接从/bin/bash调用bash可以避免:

child_process.execSync('diff <(curl a) <(curl b)', {shell: '/bin/bash'});
© www.soinside.com 2019 - 2024. All rights reserved.