How to exec commands in Node.js
The exec method executes shell commands in Node.js with buffered output, ideal for simple commands that produce small amounts of data and complete quickly. As the creator of CoreUI, a widely used open-source UI library, I’ve used exec for simple command execution in Node.js scripts throughout my 11 years of backend development. The most straightforward approach is using the exec method from the child_process module for quick shell commands that return limited output. This method buffers the entire output in memory, making it convenient for commands like git status or npm version.
Use exec from child_process module to execute shell commands with buffered output.
const { exec } = require('child_process')
exec('git status', (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`)
return
}
if (stderr) {
console.error(`Stderr: ${stderr}`)
return
}
console.log(`Output:\n${stdout}`)
})
Here exec runs the git status command in a shell environment. The callback receives three parameters: error if the command fails, stdout containing the command’s standard output, and stderr containing error output. The entire output buffers in memory until the command completes, then the callback executes with the full results. This makes exec simple for commands that complete quickly with small output, but unsuitable for long-running processes or commands producing large data streams.
Best Practice Note:
This is the approach we use in CoreUI utility scripts for simple version checks and quick Git commands. Only use exec for trusted input as it spawns a shell, making it vulnerable to command injection, prefer spawn for large outputs to avoid memory issues, and set maxBuffer option to increase the buffer size limit if needed for larger command outputs.



