2017-06-20 110 views
4

我需要使用执行一组Cassandra DB命令的nodeJS运行一个shell脚本文件。任何人都可以帮我在这里如何使用nodejs运行shell脚本文件?

里面的db.sh文件。

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

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

欢迎来到SO !.在发布问题之前请阅读以下文章: https://stackoverflow.com/help/how-to-ask – garfbradaz

回答

6

您可以使用此模块https://www.npmjs.com/package/shelljs执行任何shell命令。

const shell = require('shelljs'); 
//shell.exec(comandToExecute, {silent:true}).stdout; 
//you need little improvisation 
shell.exec('./path_to_ur_file') 
+0

这不符合目的。我需要运行本地系统中存在的脚本文件。该模块用于执行命令。您能否告诉我们如何运行一个shell脚本文件。 –

+1

仔细查看答案。这是一个如何执行shell脚本文件的例子 –

15

您可以使用nodejs的“子进程”模块在nodejs中执行任何shell命令或脚本。让我用一个示例向您展示,我正在nodejs中运行一个shell脚本(hi.sh)。

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}`); 
      } 
     }); 

在这里,当我运行该文件的NodeJS,它将执行shell文件,输出会是:

运行

node node_program.js 

输出

Hi There! 

您可以只用在exec回调提的shell命令或shell脚本执行任何脚本。

希望这会有所帮助!快乐编码:)