Node.js spawning a child process interactively with separate stdout and stderr streams

前端 未结 3 1122
攒了一身酷
攒了一身酷 2020-12-09 05:08

Consider the following C program (test.c):

#include 

int main() {
  printf(\"string out 1\\n\");
  fprintf(stderr, \"string err 1\\n\");
  ge         


        
3条回答
  •  天涯浪人
    2020-12-09 05:21

    I was just revisiting this since there is now a 'shell' option available for the spawn command in node since version 5.7.0. Unfortunately there doesn't seem to be an option to spawn an interactive shell (I also tried with shell: '/bin/sh -i' but no joy). However I just found this which suggests using 'stdbuf' allowing you to change the buffering options of the program that you want to run. Setting them to 0 on everything produces unbuffered output for all streams and they're still kept separate.

    Here's the updated javascript:

    var TEST_EXEC = './test';
    
    var spawn = require('child_process').spawn;
    var test = spawn('stdbuf', ['-i0', '-o0', '-e0', TEST_EXEC]);
    
    test.stdout.on('data', function (data) {
      console.log('stdout: ' + data);
    });
    
    test.stderr.on('data', function (data) {
      console.log('stderr: ' + data);
    });
    
    // Simulate entering data for getchar() after 1 second
    setTimeout(function() {
      test.stdin.write('\n');
    }, 1000);
    

    Looks like this isn't pre-installed on OSX and of course not available for Windows, may be similar alternatives though.

提交回复
热议问题