Performance: exec for running shell commands
Running shell commands with exec can cause high memory usage from buffering the entire output, potentially leading to buffer exceeded errors or GC pauses.
Jump into concepts and practice - no test required
const { spawn } = require('child_process');
const child = spawn('some-long-running-command');
child.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
child.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
child.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});const { exec } = require('child_process');
exec('some-long-running-command', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
});| Pattern | Buffering | Memory Usage | Output Handling | Verdict |
|---|---|---|---|---|
| exec | Buffers entire output until complete | High for large outputs due to buffering | Buffers entire output before callback | [X] Bad |
| spawn | Streams output incrementally | Low, streams data incrementally | Streams output data as it arrives | [OK] Good |
exec function in Node.js primarily do?exec function is designed to run shell commands from Node.js code.exec.exec from the child_process module in Node.js?exec is imported as const exec = require('child_process').exec;.import exec from 'child_process'; uses ES module default import incorrectly; const exec = require('exec'); tries to require a non-existent module; import { exec } from 'child_process'; is ES module named import but Node.js needs special config.test.txt?
const { exec } = require('child_process');
exec('ls', (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return;
}
if (stderr) {
console.error(`Stderr: ${stderr}`);
return;
}
console.log(`Output: ${stdout}`);
});ls lists files in the current directory. If test.txt exists, it will appear in the output.exec:
const { exec } = require('child_process');
exec('node -v', (error, stdout, stderr) => {
if (error) {
console.log(error);
}
console.log(stdout);
});exec usage correctly achieves this in Node.js?| sends output of ls to grep log to filter lines containing 'log'.ls | grep log correctly pipes output to grep for filtering; ls > grep log uses redirection to create a file; ls && grep log runs sequentially without piping; ls | find log pipes to filesystem search tool unsuitable for text filtering.