Node.js的Shell脚本和参数 [英] Node.js Shell Script And Arguments
问题描述
我需要执行在node.js中bash脚本基本上,脚本会在系统上创建用户帐户。我碰到来到这个例子这给了我一个想法,如何去关于它。然而,该脚本本身需要像用户名,口令和用户的真实姓名参数。我仍然无法弄清楚如何将这些参数传递给脚本做这样的事情:
I need to execute a bash script in node.js. Basically, the script will create user account on the system. I came across this example which gives me an idea how to go about it. However, the script itself needs arguments like the username, the password and the real name of the user. I still can't figure out how to pass those arguments to the script doing something like this:
var commands = data.toString().split('\n').join(' && ');
有没有人有一个想法如何,我可以通过这些参数,并通过一个SSH连接执行的node.js内的bash脚本。
谢谢
Does anyone have an idea how I can pass those arguments and execute the bash script within node.js over an ssh connection. thanks
推荐答案
查看文档的这里。它是如何通过命令行参数非常具体。请注意,您可以使用 EXEC
或产卵
。 产卵
对命令行参数的具体参数,而与 EXEC
你只是传递参数作为命令的一部分字符串来执行。
See the documentation here. It is very specific on how to pass command line arguments. Note that you can use exec
or spawn
. spawn
has a specific argument for command line arguments, while with exec
you would just pass the arguments as part of the command string to execute.
直接从文档,解释与评论直列
Directly from the documentation, with explanation comments inline
var util = require('util'),
spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']); // the second arg is the command
// options
ls.stdout.on('data', function (data) { // register one or more handlers
console.log('stdout: ' + data);
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
ls.on('exit', function (code) {
console.log('child process exited with code ' + code);
});
而使用EXEC
Whereas with exec
var util = require('util'),
exec = require('child_process').exec,
child;
child = exec('cat *.js bad_file | wc -l', // command line argument directly in string
function (error, stdout, stderr) { // one easy function to capture data/errors
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
最后,注意EXEC缓冲输出。如果你想流输出回客户端,你应该使用产卵
。
这篇关于Node.js的Shell脚本和参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!