How to run shell script file using nodejs?

node.jsShellCassandra

node.js Problem Overview


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)

node.js Solutions


Solution 1 - node.js

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 :)

Solution 2 - node.js

You can execute any shell command using the shelljs module

 const shell = require('shelljs')

 shell.exec('./path_to_your_file')

Solution 3 - node.js

you can go:

var cp = require('child_process');

and then:

cp.exec('./myScript.sh', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a command in your $SHELL.
Or go

cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a file WITHOUT a shell.
Or go

cp.execFile();

which is the same as cp.exec() but doesn't look in the $PATH.

You can also go

cp.fork('myJS.js', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a javascript file with node.js, but in a child process (for big programs).

EDIT

You might also have to access stdin and stdout with event listeners. e.g.:

var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
  // handle stdout as `data`
});

Solution 4 - node.js

Also, you can use shelljs plugin. It's easy and it's cross-platform.

Install command:

npm install [-g] shelljs

What is shellJS

> ShellJS is a portable (Windows/Linux/OS X) implementation of Unix > shell commands on top of the Node.js API. You can use it to eliminate > your shell script's dependency on Unix while still keeping its > familiar and powerful commands. You can also install it globally so > you can run it from outside Node projects - say goodbye to those > gnarly Bash scripts!

An example of how it works:

var shell = require('shelljs');
 
if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git');
  shell.exit(1);
}
 
// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');
 
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
  shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
  shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
  shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');
 
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
  shell.echo('Error: Git commit failed');
  shell.exit(1);
}

Also, you can use from the command line:

$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo

Solution 5 - node.js

#!/usr/bin/env node

console.log("Hello world!") // place your code here.

to execute this file:

./app.js

there should be executable permission given on file app.js

chmod u+x app.js

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionprogramoholicView Question on Stackoverflow
Solution 1 - node.jsSravanView Answer on Stackoverflow
Solution 2 - node.jsMustafa MamunView Answer on Stackoverflow
Solution 3 - node.jsLennon McLeanView Answer on Stackoverflow
Solution 4 - node.jsAli HallajiView Answer on Stackoverflow
Solution 5 - node.jsDeeksha PanditView Answer on Stackoverflow