Questions And Answers

More Tutorials

NodeJS Executing files or commands with Child Processes

Spawning a new process to execute a command

To spawn a new process in which you need unbuffered output (e.g. long-running processes which might print output over a period of time rather than printing and exiting immediately), use child_process.spawn().

This method spawns a new process using a given command and an array of arguments. The return value is an instance of ChildProcess, which in turn provides the stdout and stderr properties. Both of those streams are instances of stream.Readable.

The following code is equivalent to using running the command ls -lh /usr.

const spawn = require('child_process').spawn;
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
 console.log(`stdout: ${data}`);
ls.stderr.on('data', (data) => {
 console.log(`stderr: ${data}`);
ls.on('close', (code) => {
 console.log(`child process exited with code ${code}`);

Another example command:

zip -0vr "archive" ./image.png
Might be written as:
spawn('zip', ['-0vr', '"archive"', './image.png']);


In this page (written and validated by ) you learned about NodeJS Executing files or commands with Child Processes . What's Next? If you are interested in completing NodeJS tutorial, your next topic will be learning about: NodeJS Exception handling.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.