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?