Not receiving stdout from nodejs spawned process

后端 未结 3 1858
青春惊慌失措
青春惊慌失措 2021-02-13 11:08

I\'m trying to have nodejs interact with adventure, an old text based game. The idea is to open adventure as a child process and then play the game by writing

3条回答
  •  面向向阳花
    2021-02-13 11:34

    After going through the Nodejs documentation a few more times, I convinced myself I was either missing something pretty big, or the spawn command wasn't working correctly. So I created a github issue.

    And the answer was immediately posted: the child process can't buffer output if you want fast access.

    So to achieve what I was originally looking for:

    var childProcess = require('child_process');
    var spawn = childProcess.spawn;
    var child = spawn('unbuffer', 'adventure');
    
    console.log("spawned: " + child.pid);
    
    child.stdout.on('data', function(data) {
      console.log("Child data: " + data);
    });
    child.on('error', function () {
      console.log("Failed to start child.");
    });
    child.on('close', function (code) {
      console.log('Child process exited with code ' + code);
    });
    child.stdout.on('end', function () {
      console.log('Finished collecting data chunks.');
    });
    

    With the functional difference being the use of unbuffer, a command that disables output buffering.

提交回复
热议问题