How to Use spawn in Node.js: Simple Guide with Examples
In Node.js, you use
spawn from the child_process module to start a new process that runs a command. It lets you handle the output and errors of that command asynchronously, making it ideal for running system commands or other programs without blocking your main code.Syntax
The spawn function is called with the command to run and an array of arguments. It returns a ChildProcess object that you can use to listen for output, errors, and when the process closes.
- command: The program or command you want to run.
- args: An array of strings representing command line arguments.
- options: Optional settings like environment variables or working directory.
javascript
const { spawn } = require('child_process'); const child = spawn(command, args, options); child.stdout.on('data', (data) => { console.log(`Output: ${data}`); }); child.stderr.on('data', (data) => { console.error(`Error: ${data}`); }); child.on('close', (code) => { console.log(`Process exited with code ${code}`); });
Example
This example runs the ls command to list files in the current directory. It shows how to capture and print the output and handle errors.
javascript
const { spawn } = require('child_process'); const ls = spawn('ls', ['-lh', '.']); ls.stdout.on('data', (data) => { console.log(`Output:\n${data}`); }); ls.stderr.on('data', (data) => { console.error(`Error:\n${data}`); }); ls.on('close', (code) => { console.log(`Process exited with code ${code}`); });
Output
Output:
-rw-r--r-- 1 user staff 1234 Jun 10 12:00 example.txt
-rw-r--r-- 1 user staff 5678 Jun 10 12:00 index.js
Process exited with code 0
Common Pitfalls
Common mistakes when using spawn include:
- Not handling
stderroutput, which can hide errors. - Forgetting to listen for the
closeevent to know when the process ends. - Passing arguments as a single string instead of an array, which causes errors.
- Assuming
spawnbuffers output likeexec; it streams data, so you must handle chunks.
javascript
const { spawn } = require('child_process'); // Wrong: args as string // const child = spawn('ls -lh'); // This will fail // Right: args as array const child = spawn('ls', ['-lh']); child.stdout.on('data', (data) => { console.log(`Output: ${data}`); }); child.stderr.on('data', (data) => { console.error(`Error: ${data}`); }); child.on('close', (code) => { console.log(`Process exited with code ${code}`); });
Quick Reference
Remember these tips when using spawn:
- Use
spawnfor long-running processes or streaming output. - Always pass command arguments as an array.
- Listen to
stdout,stderr, andcloseevents. - Use
optionsto set environment or working directory if needed.
Key Takeaways
Use spawn from child_process to run commands without blocking Node.js.
Pass command arguments as an array, not a single string.
Listen to stdout, stderr, and close events to handle output and process end.
spawn streams output, so handle data in chunks as it arrives.
Use spawn options to customize environment or working directory.