How to run shell script file using nodejs?

2020-01-24 12:21发布

问题:

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)

回答1:

You can execute any shell command using the shelljs module

 const shell = require('shelljs')

 shell.exec('./path_to_your_file')


回答2:

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').exec;
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 :)



回答3:

you can go:

require('./myScript.sh');

just make sure to add shebang in bash script.

#! /bin/bash