How to execute an external program from within Node.js?

Sometimes, we want to execute an external program from within Node.js.

In this article, we’ll look at how to execute an external program from within Node.js.

How to execute an external program from within Node.js?

To execute an external program from within 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 an external program from within Node.js, we can use the child_process module’s exec method.