shell命令包含管道,将child_process.exec()等待所有操作完成后再调用回调



https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback有这样的例子,

const exec = require('child_process').exec;
const child = exec('cat *.js bad_file | wc -l',
  (error, stdout, stderr) => {
    console.log(`stdout: ${stdout}`);
    console.log(`stderr: ${stderr}`);
    if (error !== null) {
      console.log(`exec error: ${error}`);
    }
});

exec()中的shell命令中有一个管道,我的问题是,回调是在"cat"完成后调用还是在"wc"完成后才调用?

这种情况下会发生什么:

const child = exec('cat *.js; ls -l', callback);

谢谢!

我在Javascript中运行了一个示例,exec()作为任何带有回调的函数;如果在触发回调之前没有错误,则执行所有操作。

JSON文件为例:

[
  {
    "test" : {
      "test1" : 1,
      "test2" : 2,
      "test3" : "this is a string"
    }
  }  
]

代码:

const exec = require('child_process').exec;
const child = exec('cat json.json | wc -l',
  (error, stdout, stderr) => {
    console.log('stdout:', stdout);
    if (error !== null) {
      console.log('exec error: ', error);
    }
  }
);

输出:

stdout:       9

最新更新