How to execute shell script file from Nodejs Application


Sometimes, We want to execute the shell or bash script files from nodejs code, This tutorial talks about how to run shell script files from a javascript code and commandline in nodejs application.

Why we need to run shell script file from nodejs programm

  • It is helpful to automate the server side tasks with running unix shell script from javascript program
  • Batch job execution to send email or copy or delete or sync files between file systems.
  • It improves performance when you are executing OS related commmands to interact with file system from javascript.

With nodejs, Shell scripts are executed with taking input and process and sends output from a code.

There are multiple ways we can do execution of shell script from a command line in NodeJS application.

  • Inbuilt child_process module : You can have a shell or bash script file and execute from javascript code using child_process module
  • ShellJS module: In this approach, script files are not required, instead It provides portable independent unix commands from javascript.

Execute shell/bash script file from nodejs application

child_process module allows you to launch shell or bash window and executes the script file in shell window.

It provides new child process for a main nodejs process in a program.

It provides two functions to execute script files from nodejs application.

  • spawn:
  • exec :

child process exec function

exec function creates a new shell and executes shell script file from a newly shell window.

Output of execution is buffered and can be used in nodejs callbacks.

Here is an syntax

child_process.exec(command or script file,[, options][, callback]);


It has three parameters
- command or script file : can be unix commands or shell/bash script file
- options : are command line arguments can be passed
- callback : It is an function with `error`, `stdin` and `stdout` parameters are of type string or Buffer type in nodejs.


Here is an javascript code to remove an files from a folder
First import child_process module using require command
```javascript
var cp = require('child_process');

delete.js

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

exec("rm -rf",["dist"] (error, stdout, stderr) => {
    if (error) {
        console.log('Error in removing files');
        return;
    }
    if (stderr) {
        console.log('an error with file system'');
        return;
    }
    console.log('Result of rm -rf command output',);
});

Running below command deletes all the files from dist folder

node delete.js

Next, Let’s try to run a shell script from Nodejs program

Let’s have a sample shell script file first.sh

echo 'Hello world'
const { exec } = require("child_process");
cp.exec('./first.sh', (error, stdout, stderr) => {
  // catch err, stdout, stderr
    if (error) {
        console.log('Error in removing files');
        return;
    }
    if (stderr) {
        console.log('an error with file system');
        return;
    }
    console.log('Result of shell script execution',stdout);
});

child process spawn function

spawn is another way of shell script execution from nodejs program.

It creates new child process and executes shell script and returns the data using stream API. As you are using stream API, you have to write a listener to handle the data.

stdout and stderr are catched written data using stream with listenng with data events

Here is an example code to run bash script file from nodejs program

const cp = require("child_process");

cp.spawn('./first.sh', function(err, stdout, stderr) {

stdout.on("data", data => {
        console.log('Output of script execution');
});

stderr.on("data", data => {
        console.log('an error with file system'');
});

Difference between spawn and exec in nodejs

Both are used to run script or commands from a nodejs program and creates a new process and lauches shell window.

They both have a difference in how the data is returned.

exec stores the data in a buffer from a execution output , where as spawn streams the data and listeners catchs data.

If script files returns small amount of data, you can use exec process. spawn is best suitable for which script returns large amount of data.

Nodejs ShellJS Module

ShellJS is a npm library to run UNIX commands in cross platforms using javascript code.

It provides an commandline tool called shx after installing it globally or locally in a project

First, Install library

npm i shelljs --save

This package provides following unix commands as part of command line as well as from javascript.

  • touch
  • cat
  • rm
  • which
  • cd
  • cp if you want to check java is not installed on unix machine
var shell = require('shelljs');

if (!shell.which('java')) {
  shell.echo('Java version is not installed');
  shell.exit(1);
}

To remove files from a directory, you can use

shell.rm('-rf', 'dist/public');

To copy files from one directory to another directory recursively

shell.cp('-R', 'dist/', 'release');

or you can use the same above from command line using shx tool

$ shx which java
$ shx rm -rf dist/public
$ shx cp -R dist release

With this approach, No need of writing bash or shell script files, Instead you can controll from everything from javascript code.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.