DEV Community

Cover image for This Node.js Package Changes Everything About Running Shell Commands
Dhanush N
Dhanush N

Posted on • Originally published at dhanushnehru.Medium

This Node.js Package Changes Everything About Running Shell Commands

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
Enter fullscreen mode Exit fullscreen mode

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);
  });
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
andriy_ovcharov_312ead391 profile image
Andriy Ovcharov

Interesting. Thanks for sharing!

Collapse
 
dhanushnehru profile image
Dhanush N

You are welcome