简体   繁体   中英

No carriage returns when using Node.js child processes?

I have a Node.js script that runs to do some database operations. I create a couple of child processes using the spawn functionality. The strange thing is, I stop getting carriage returns in my output. For example:

running...
          more output.
                      more output.
                                  complete.

The setup is as follows:

  • Main parent process: kicks off child piped to tee
    • Main child process: does majority of db transactions
      • Child subprocess 1: opens a VPN tunnel and stays running through entire execution
      • Child subprocess 2: Runs a brief script then terminates

I'm spawning the child processes in this manner:

var spawn = require('child_process').spawn;
STATE.childProcesses.logged = spawn('sh',['-c', cmd],{
  stdio: [0]
});

STATE.childProcesses.logged.stdout.on('data', function (data) {
  process.stdout.write(data.toString().replace(/\n/g, "\r\n"));
});

STATE.childProcesses.logged.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});

STATE.childProcesses.logged.on('exit', function (code) {
  console.log('main child process exited with code ' + code);
});

I was able to work around the issue by doing a .replace(/\\n/g, "\\r\\n") on the child process's stdout data as seen above.

However, now when the main parent process terminates, the bash shell it was running in is suffering from a similar issue: it outputs neither carriage returns nor newlines. Also text that I type doesn't show up. If I close the Terminal window it's running in (Mac OSX) and reopen the issue goes away.

I can verify that when the parent process terminates, all child processes are also terminated. At least, I call .kill('SIGINT') on all of them and I'm able to close Terminal without any warnings about child processes getting terminated.

I'm wondering if it has something to do with the routing of stdio for the spawned processes, but can't figure it out. Any tips greatly appreciated!

I was able to solve the issue of bash getting screwed up post execution by being careful about child process termination. Turns out I wasn't terminating one of the child processes properly and once I made sure it was dead before ending the parent process the bash issue went away.

I never did figure out why I needed to have the .replace(/\\n/g, "\\r\\n") though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM