How to execute and get the output of a shell command in Node.js?

Sometimes, we want to execute and get the output of a shell command in Node.js.

In this article, we’ll look at how to execute and get the output of a shell command in Node.js.

How to execute and get the output of a shell command in Node.js?

To execute and get the output of a shell command in Node.js, we can use the child_process module’s exec method.

For instance, we write

const {
  exec
} = require('child_process');

exec(command, (error, stdout, stderr) => {
  console.log(error, stdout, stderr)
});

to call exec with the command string we want to run.

The 2nd argument is a callback that has the stdout and stderr output after running the command.

error has the error that’s thrown when the command is run.

Conclusion

To execute and get the output of a shell command in Node.js, we can use the child_process module’s exec method.