Categories
JavaScript Answers

How to execute bash command in Node.js and get exit code?

Spread the love

To execute bash command in Node.js and get exit code, we call exec.

For instance, we write

const dir = exec("ls -la", (err, stdout, stderr) => {
  console.log(stdout);
});

dir.on("exit", (code) => {
  console.log(code);
});

to call exec to run the ls -la command.

We get the output from stdout in the callback.

Then we call dir.on to listen for the exit event.

And we get the exit code from code in the callback.

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 *