Node.js — Processes
Child Process Module
const { exec, spawn } = require('child_process');
exec
Runs a command in a shell:
exec('ls -la', (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return;
}
console.log(stdout);
});
spawn
Launches a new process:
const child = spawn('ls', ['-la']);
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}`);
});
fork
Creates a new Node.js process:
const { fork } = require('child_process');
const child = fork('worker.js');
child.on('message', (msg) => {
console.log('Message from child:', msg);
});
child.send({ task: 'process' });
Environment
const child = spawn('node', ['script.js'], {
env: { ...process.env, NODE_ENV: 'production' },
cwd: '/path/to/directory'
});
Mini Practice
- Execute a shell command
- Spawn a child process
- Fork a Node.js process
- Communicate between processes
Up Next
Continue with Environment Variables — using env vars.
Related Topics
Frequently Asked Questions about Processes
What is Processes in Node.js?
Processes is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Processes?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Processes.
Why is Processes important in Node.js?
Processes is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.