{

How to execute shell script file from Nodejs Application


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 command line in nodejs application.

Why do we need to run the shell script file from the nodejs program?

  • It is helpful to automate the server-side tasks by running a UNIX shell script from a 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 commands to interact with the file system from javascript.

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

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

  • Inbuilt child_process module: You can have a shell or bash script file and execute from javascript code using the 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 a shell or bash window and execute the script file in a shell window.

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

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

  • spawn:
  • exec :

child process exec function

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

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

Here is a 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 that can be passed
- callback: It is a function with `error`, `stdin`, and `stdout` parameters of type string or Buffer type in nodejs.


Here is a javascript code to remove a file from a folder
First, import the 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 the below command deletes all the files from the dist folder

node delete.js

Next, Let’s try to run a shell script from the 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 the nodejs program.

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

stdout and stderr are caught written data using stream with listening 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 spawn and exec are used to run scripts or commands from a nodejs program, as well as to start a new process and launch a shell window.

They both have a difference in how to return data.

exec stores the data in a buffer from an execution output, whereas spawn streams the data, and listeners catch data.

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

Nodejs ShellJS Module

ShellJS is an npm library to run UNIX commands across platforms using javascript code.

It provides a command-line tool called shx after installing it globally or locally in a project

First, Install a library

npm i shelljs --save

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

  • touch
  • cat
  • rm
  • which
  • cd
  • cp if you want to check java is not installed on a 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 the 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 control everything from javascript code.

Conclusion

To Sum up, You learned how to execute bash or shell script from the Nodejs program using ShellJS library as well as spawn and exec functions.

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.