Categories
JavaScript Answers

How to execute shell command with Node.js?

Spread the love

Sometimes, we want to execute shell command with Node.js.

In this article, we’ll look at how to execute shell command with Node.js.

How to execute shell command with Node.js?

To execute shell command with Node.js, we can use the child_process module’s spawn function.

For instance, we write

const runCmd = (cmd, args, callBack) => {
  const { spawn } = require("child_process");
  let child = spawn(cmd, args);
  let resp = "";

  child.stdout.on("data", (buffer) => {
    resp += buffer.toString();
  });
  child.stdout.on("end", () => {
    callBack(resp);
  });
};

runCmd("ls", ["-l"], (text) => {
  console.log(text);
});

to call the child_process module’s spawn function with the cmd command string and the args argument string array.

We call stdout.on to listen to the data event which has the output of the cmd command.

And then we call on again to listen to the end event which is emitted when the command finishes running.

We run callBack in the end event callback with the resp string.

Conclusion

To execute shell command with Node.js, we can use the child_process module’s spawn function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *