1

I'm trying to understand how node works when it comes to child processes and event listeners. So, if I put the code below in a file and run it at the command line with node all at once, I can see the output of pwd logged out, but if I run each line individually in node, it doesn't show up. If I put the second two lines on one line in the REPL separated by a semicolon, though, it does work.

const { spawn } = require('child_process');

const child = spawn('pwd', []);

child.stdout.on('data', d => console.log(d));

I thought this might have something to do with too long of time elapsing between the spawn and adding the event listener with .on, so I tried printing out a bunch of numbers to kill time in between, but that didn't make a difference.

I imagine this has to do with how node/JS are compiled and run but I'm not sure. In short, why does this work in a file, and not when it's run interactively in the node REPL? Isn't the file being read and executed in sequence as well?

etd
  • 31
  • 3
  • 1
    I think your first assumption is correct. You might want to use [exec](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback) for this. – Khauri Oct 19 '19 at 22:28
  • Your interactive REPL statements are not run synchronously in the same tick if you enter them separately, thus the `data` event has a chance to fire in between. Have a look at [this answer](https://stackoverflow.com/a/30906613/1048572) for why that cannot happen when the event handler is installed synchronously (even if you kill time with a busy waiting loop in between). – Bergi Oct 19 '19 at 23:10

0 Answers0