How to run shell script file using nodejs?

programoholic picture programoholic · Jun 20, 2017 · Viewed 117.4k times · Source

I need to run a shell script file using nodeJS that executes a set of Cassandra DB commands. Can anybody please help me on this.

inside db.sh file:

create keyspace dummy with   replication = {'class':'SimpleStrategy','replication_factor':3}

create table dummy (userhandle text, email text primary key , name text,profilepic)

Answer

Sravan picture Sravan · Jun 21, 2017

You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script(hi.sh) with in nodejs.

hi.sh

echo "Hi There!"

node_program.js

const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
        (error, stdout, stderr) => {
            console.log(stdout);
            console.log(stderr);
            if (error !== null) {
                console.log(`exec error: ${error}`);
            }
        });

Here, when I run the nodejs file, it will execute the shell file and the output would be:

Run

node node_program.js

output

Hi There!

You can execute any script just by mentioning the shell command or shell script in exec callback.

Hope this helps! Happy coding :)