如何使用Node.js运行Shell脚本文件?

81

我需要使用nodeJS运行一个shell脚本文件,执行一系列的Cassandra数据库命令。请问有人可以帮我吗。

在db.sh文件中:

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

create table dummy (userhandle text, email text primary key , name text,profilepic)
4个回答

159
你可以使用Node.js的"child process"模块来在Node.js中执行任何shell命令或脚本。让我用一个例子来展示,我正在在Node.js中运行一个名为hi.sh的shell脚本。

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

当我运行Node.js文件时,它会执行Shell文件并输出:

运行

node node_program.js

输出

Hi There!

只需在exec回调中提及 shell 命令或 shell 脚本,即可执行任何脚本。


1
请勿使用流输出,而应改用spawn - Dimitri Kopriwa
@DimitriKopriwa,你能提供一个关于spawn的例子吗? - Don Srinath
2
示例在此处:https://github.com/rollup-umd/build/blob/master/src/index.js - Dimitri Kopriwa
1
这个导入看起来更干净:const { exec } = require('child_process') - Stanley

133
您可以使用shelljs模块执行任何shell命令。
 const shell = require('shelljs')

 shell.exec('./path_to_your_file')

1
这并不符合要求。我需要运行本地系统中存在的脚本文件。该模块用于执行命令。请问如何运行shell脚本文件? - programoholic
71
仔细查看答案。这是执行shell脚本文件的示例。 - Mustafa Mamun
1
正如答案中所提到的,最好使用shelljs运行bash脚本,而不是逐个运行命令。 - Akhil S

11

你可以去:

var cp = require('child_process');

然后:

cp.exec('./myScript.sh', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});
在您的$SHELL中运行命令。
或者执行
cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

不使用shell运行文件。
或者直接执行

cp.execFile();

这与cp.exec()相同,但不会在$PATH中查找。

您也可以执行以下操作:

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

为了在 node.js 中运行 JavaScript 文件,可以使用子进程(适用于大型程序)。

编辑

你可能还需要使用事件监听器访问 stdin 和 stdout。例如:

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

1
这样做不行。你不能要求 Bash 脚本,只能要求 Node 模块。 - Harrison Cramer
1
@HarryCramer 我不是。 - Lennon McLean

9

此外,您可以使用 shelljs 插件。

它易于使用且跨平台。

安装命令:

npm install [-g] shelljs

什么是 shellJS

ShellJS 是一个基于 Node.js API 实现 Unix shell 命令的跨平台程序(Windows/Linux/OS X)。使用它可以消除你的 shell 脚本对 Unix 的依赖,同时保留熟悉和强大的命令。你还可以全局安装它,这样你就可以在 Node 项目之外运行它,不再需要编写混乱的 Bash 脚本了!

以下是其工作原理的示例:

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

此外,您还可以从命令行中使用:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接