Run Bash Script from Node

09-22-2018

I recently needed a way to execute a bash script from a Node application. The premise was simple, to create an authorization protected Node/Express endpoint that could execute a bash script that lives alongside my app. My script does tasks like moving local log files and restarting processes. Node makes this extremely easy to do.

Problem: Run bash script from Node Application

Solution:

By leveraging the child processes in Node I can spawn a new child process to execute the script. Spawning allows separate child processes to run asynchronously. Here I will show an example using a setInterval(), but this can easily be added to any other portion of your Node app, like a JWT protected endpoint.

app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14

'use strict'

const child_process = require("child_process");

setInterval(() => {

const child = child_process.spawn('bash', [__dirname + '/myscript.sh']);

child.on('exit', () => {
console.log('process complete');
});

}, 3000);

This will simply execute myscript.sh every 3 seconds, console logging when the _child_process_ is complete.

To breakdown each line:

const child = child_process.spawn('bash', [__dirname + '/myscript.sh']);

This is creating a new constant variable call child and setting it to a new child_process.spawn(). The spawn will the execute our myscript.sh as a ‘bash’ script.

The child_process.spawn() produces a few different events, here we are listening for the exit event and console.log()’ing that the process completed.