Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run shell script file using nodejs?

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) 
like image 365
programoholic Avatar asked Jun 20 '17 08:06

programoholic


People also ask

How run js file in shell script?

You can Run your JavaScript File from your Terminal only if you have installed NodeJs runtime. If you have Installed it then Simply open the terminal and type “node FileName. js”. If you don't have NodeJs runtime environment then go to NodeJs Runtime Environment Download and Download it.


2 Answers

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

like image 194
Sravan Avatar answered Sep 22 '22 20:09

Sravan


You can execute any shell command using the shelljs module

 const shell = require('shelljs')   shell.exec('./path_to_your_file') 
like image 41
Mustafa Mamun Avatar answered Sep 21 '22 20:09

Mustafa Mamun