As I read from the child_process
module documentation of Node.js, I understand the difference between exec
and spawn
. The most crucial difference that is also highlighted in a similar StackOverflow question about the Spawn vs Exec:
The main difference is that spawn is more suitable for long-running processes with huge output. That's because spawn streams input/output with a child process. On the other hand, exec buffers output in a small (by default 200K) buffer.
However, I noticed, thanks to TS Intellisense that both exec
and spawn
function return similar object of type ChildProcess
. So, I could technically write this for the exec
function using stdout
as stream and it works:
function cmdAsync (cmd, options) {
return new Promise((resolve) => {
const proc = exec(cmd, options);
proc.stdout?.pipe(process.stdout);
proc.on('exit', resolve);
});
}
cmdAsync('node server/main.mjs');
And without any buffer time/delay, I could see the logs generated by server/main.mjs
file being piped into the parent process's stdout
stream.
So, my question is exactly where the buffering is happening and how the streaming behavior is different for exec
than spawn
function! Also, can I rely of this feature even if it is undocumented?