Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Spawn vs. Execute

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?

like image 922
Harrison Cramer Avatar asked Feb 09 '18 03:02

Harrison Cramer


People also ask

What does exec () do in Nodejs?

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() .

What is spawn in Nodejs?

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.


1 Answers

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

like image 64
Vasyl Moskalov Avatar answered Oct 02 '22 15:10

Vasyl Moskalov