Execute Shell Script in Node.js

In this short article, we’ll learn how to execute the shell script using Node.js.

Use the shelljs Module to Execute Shell Script in Node.js

On top of Node.js API, the ShellJS is a portable implementation of Unix shell commands. You could use it to remove your shell script dependency on Unix while keeping your instructions acquainted and powerful.

You can additionally install it globally to run it from outside Node tasks. You can discover more information about the ShellJS documentation for shelljs.

Syntax:

exec(command [, options] [, callback])

The following are different options for Node.js child_process.exec().

  • async: async means Asynchronous execution. It’ll be set to true if the callback is provided regardless of the value passed. The default value is false.
  • silent: Don’t write program output to console. The default value is false.
  • encoding: Encoding of the characters to be used. It affects the values returned to stdout and stderr and what is written to stdout and stderr when not in silent mode. The default value is utf8.

We will focus on how to execute a shell script in Node.js using the shelljs module.

First, install the shelljs library using the following command.

$ npm i shelljs

The command below will check the version of npm.

const shell = require('shelljs')
shell.exec("npm --version")

Instead of a command, you can also specify the path of your shell file.

Output:

8.1.2

Run Demo