使用外部包:
您可以使用shelljs https://github.com/arturadib/shelljsnpm 包
不使用外部包:利用nodejschild_process
模块。下面是实现
1.exec_process.js
var exec = require('child_process').exec;
var result = function(command, cb){
var child = exec(command, function(err, stdout, stderr){
if(err != null){
return cb(new Error(err), null);
}else if(typeof(stderr) != "string"){
return cb(new Error(stderr), null);
}else{
return cb(null, stdout);
}
});
}
exports.result = result;
2.临时文件
#! /usr/bin/bash
pwd
git --version
3.app.js
var execProcess = require("./exec_process.js");
execProcess.result("sh temp.sh", function(err, response){
if(!err){
console.log(response);
}else {
console.log(err);
}
});
要运行该应用程序,您可以尝试node app.js
Output:
/root
git 版本 1.8.1.2
同样,您可以在 shell 脚本文件中添加任何命令并使用 node 运行它。演示和源代码发布于runnable http://goo.gl/EZZ7fP.
建议检查git-extras https://github.com/tj/git-extras它涵盖了通过命令行使用 git 的所有用例。