How to Run a Shell Commands in Node.js

Something that seems to surprise people is that Node.js allows you to run shell commands within your application, giving you a way to interact with the system's shell.

This capability comes from the child_process module, which provides various methods to spawn child processes.

Here's how:

Using exec

The exec method is perfect for executing simple shell commands where you want to handle the output all at once.

It runs the command inside a shell, buffers the output, and delivers it back to your application after the command finishes executing.

It's really easy to use. Here's the simplest example:

const { exec } = require("node:child_process");

exec('echo "Hello, world!"');

Now, you might need to use the output from something like this to make it useful.

Thankfully, you can pass a callback to do this:

const { exec } = require("node:child_process");

exec('echo "Hello, world!"', (error, stdout, stderr) => {
  if (error) {
    console.error(`Error: ${error}`);
    return;
  }
  console.log(`Output: ${stdout}`); // "Output: Hello, world!"
});

And just like that, you are running shell commands. ✌️

Nodejs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.