찾다

 >  Q&A  >  본문

node.js - node的child_process.spawn(...[, options])怎么写多个options?

如果有多个grep,怎么写到上面的语句中?例如cat /dev/urandom |od -x|tr -d ' '|head -n 1

在网上找了下,发现用以下的方法也行,使用spawnexec有什么区别呢?

const exec = require('child_process').exec;
exec('cat /dev/urandom |od -x|tr -d ' '|head -n 1', (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});
PHP中文网PHP中文网2783일 전642

모든 응답(2)나는 대답할 것이다

  • 天蓬老师

    天蓬老师2017-04-17 15:38:29

    如果不封装的话,你需要监听多个事件,举例说cat /dev/urandom |od -x|tr -d ' '|head -n 1

    const spawn = require('child_process').spawn;
    const cat = spawn('cat', ['/dev/urandom']);
    const od = spawn('od',['-x']);
    const tr = spawn('tr',['-d'," "]);
    const head = spawn('head', ['-n',1]);
    
    cat.stdout.on('data', data => od.stdin.write(data));
    cat.on('close', (code) => od.stdin.end());
    
    od.stdout.on('data', data => tr.stdin.write(data));
    od.on('close', (code) => tr.stdin.end());
    
    tr.stdout.on('data', data => head.stdin.write(data));
    tr.on('close', (code) => head.stdin.end());
    
    head.stdout.on('data', data => console.log(`${data}`));
    head.stdin.on('error',err=>head.stdin.end());

    也可以在spwan创建子进程的时候制定一下pipe管道,比如这样

    const spawn = require('child_process').spawn;
    const cat = spawn('cat', ['/dev/urandom'], {stdio: 'pipe'});
    const od = spawn('od',['-x'], {stdio: [cat.stdout, 'pipe', 'pipe']});
    const tr = spawn('tr',['-d',' '], {stdio: [od.stdout, 'pipe', 'pipe']});
    const head = spawn('head', ['-n',1], {stdio: [tr.stdout, 'pipe', 'pipe']});
    
    head.stdout.on('data', data => console.log(`${data}`));
    head.stdin.on('error',err=>head.stdin.end());

    实际环境下,还要处理stderr那边的信息

    회신하다
    0
  • 天蓬老师

    天蓬老师2017-04-17 15:38:29

    你给的例子没有grep呀?

    https://nodejs.org/api/child_...

    多个options 以数组的形式作为 第二个参数传递: ls -lh /usr

    const spawn = require('child_process').spawn;
    const ls = spawn('ls', ['-lh', '/usr']);

    你给的例子cat /dev/urandom |od -x|tr -d ' '|head -n 1

    就照着你截图的那个管道分开做:

    // cat /dev/urandom
    const cat = spawn('cat',['/dev/urandom']);
    //od -x
    const od = spawn('od',['-x']);
    //tr -d ' '
    const tr = spawn('tr', ['-d',"' '"]);
    //head -n 1
    const head = spwan('head', ['-n','1']);

    然后管道的话看你截图那个例子怎么写的咯,就是回调里执行下一个指令的样子

    회신하다
    0
  • 취소회신하다