如何使用nodejs运行shell脚本文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44647778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:18:02  来源:igfitidea点击:

How to run shell script file using nodejs?

node.jsshellcassandra

提问by programoholic

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.

我需要使用执行一组 Cassandra DB 命令的 nodeJS 运行 shell 脚本文件。任何人都可以帮我解决这个问题。

inside db.sh file:

在 db.sh 文件中:

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

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

回答by Sravan

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.

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

hi.sh

嗨.sh

echo "Hi There!"

node_program.js

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:

在这里,当我运行 nodejs 文件时,它将执行 shell 文件,输出将是:

Run

node node_program.js

output

输出

Hi There!

You can execute any script just by mentioning the shell command or shell script in execcallback.

您可以通过在exec回调中提及 shell 命令或 shell 脚本来执行任何脚本。

Hope this helps! Happy coding :)

希望这可以帮助!快乐编码:)

回答by Mustafa Mamun

You can execute any shell command using the shelljs module

您可以使用shelljs 模块执行任何 shell 命令

 const shell = require('shelljs')

 shell.exec('./path_to_your_file')

回答by Lennon McLean

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

在 $SHELL 中运行命令。
或者去

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.

这与 cp.exec() 相同,但不在 $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).

使用 node.js 运行 javascript 文件,但在子进程中(对于大程序)。

EDIT

编辑

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

您可能还必须使用事件侦听器访问 stdin 和 stdout。例如:

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

回答by Ali Hallaji

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

此外,您可以使用shelljs插件。这很容易,而且是跨平台的。

Install command:

安装命令:

npm install [-g] shelljs

What is shellJS

什么是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!

ShellJS 是基于 Node.js API 的 Unix shell 命令的可移植 (Windows/Linux/OS X) 实现。您可以使用它来消除您的 shell 脚本对 Unix 的依赖,同时仍然保留其熟悉而强大的命令。您还可以全局安装它,以便您可以从 Node 项目外部运行它 - 告别那些粗糙的 Bash 脚本!

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