Simplify Running Shell Commands in Node.js
Running shell commands from Node.js scripts is common but can get tricky when you want clean, reliable output handling for both asynchronous and synchronous execution. Thatβs where node-cmd-exec steps in β a lightweight, zero-dependency npm package to execute shell commands effortlessly in Node.js.
What is node-cmd-exec?
node-cmd-exec is a utility package designed to simplify running terminal commands from Node.js. It supports:
Asynchronous execution with Promise-based API and optional callbacks
Synchronous execution that returns output and errors gracefully
Cross-platform support β works on Windows, macOS, and Linux
Returns both standard output (stdout) and standard error (stderr) with complete error context
Why use node-cmd-exec?
The native Node.js child_process module can be verbose and error-prone when handling complex command execution flows, especially if you want consistent output regardless of success or failure.
node-cmd-exec
abstracts away this complexity with a clean and robust API so you can focus on your business logic instead of process management.
Quick Start
Install it via npm:
npm install node-cmd-exec
Asynchronous example (Promise):
const nodeCmd = require('node-cmd-exec');
nodeCmd.run('ls -la')
.then(({ stdout, stderr }) => {
console.log('Directory listing:', stdout);
if (stderr) console.error('Errors:', stderr);
})
.catch(({ err, stdout, stderr }) => {
console.error('Command failed:', err);
console.log('Partial output:', stdout);
});
Synchronous example:
const result = nodeCmd.runSync('ls -la');
if (result.error) {
console.error('Sync command error:', result.stderr);
} else {
console.log('Sync output:', result.stdout);
}
Where to find it?
Your stars and contributions are very welcome! π
Conclusion
If you frequently need to run shell commands within Node.js applications or CLI tools, give node-cmd-exec a try β it makes command execution clean, simple, and predictable.
Happy coding! π
Top comments (2)
Interesting. Thanks for sharing!
You are welcome