In an online training video I am watching to learn Node, the narrator says that "spawn is better for longer processes involving large amounts of data, whereas execute is better for short bits of data."
Why is this? What is the difference between the child_process spawn and execute functions in Node.js, and when do I know which one to use?
The exec() function in Node. js creates a new shell process and executes a command in that shell. The output of the command is kept in a buffer in memory, which you can accept via a callback function passed into exec() .
spawn() : The spawn function launches a command in a new process and you can use it to pass that command any arguments. It's the most generic spawning function and all other functions are built over it [docs]. child_process.
The main difference is the spawn
is more suitable for long-running process with huge output. spawn
streams input/output with child process. exec
buffered output in a small (by default 200K) buffer. Also as I know exec
first spawn subshell, then try to execute your process. To cut long story short use spawn
in case you need a lot of data streamed from child process and exec
if you need such features as shell pipes, redirects or even you need exec more than one program in one time.
Some useful links - DZone Hacksparrow
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With