Piping data from child to parent in nodejs

前端 未结 3 1439
你的背包
你的背包 2020-12-31 11:28

I have a nodejs parent process that starts up another nodejs child process. The child process executes some logic and then returns output to the parent. The output is large

3条回答
  •  星月不相逢
    2020-12-31 11:45

    You can do this with fork()

    I just solved this one for myself...fork() is the the higher level version of spawn, and it's recommended to use fork() instead of spawn() in general.

    if you use the {silent:true} option, stdio will be piped to the parent process

              const cp = require('child_process');
    
              const n = cp.fork(, args, {
                  cwd: path.resolve(__dirname),
                  detached: true,
               });
    
              n.stdout.setEncoding('utf8');
    
              // here we can listen to the stream of data coming from the child process:
              n.stdout.on('data', (data) => {
                ee.emit('data',data);
              });
    
              //you can also listen to other events emitted by the child process
              n.on('error', function (err) {
                console.error(err.stack);
                ee.emit('error', err);
              });
    
              n.on('message', function (msg) {
                ee.emit('message', msg);
              });
    
              n.on('uncaughtException', function (err) {
                console.error(err.stack);
                ee.emit('error', err);
              });
    
    
              n.once('exit', function (err) {
                 console.error(err.stack);
                 ee.emit('exit', err);
              });
    

提交回复
热议问题