NodeJS 做到,事實上,它是包含在下載的示例之一。 使用它以交互或有益的( 可能是多個) Javascript中編寫shell腳本。
例如:#!/usr/local/bin/node
var sys = require('sys'),
exec = require('child_process').exec;
// Run `ls`:
exec('ls -lh /usr', function(error, output, erroutput) {
sys.print('output: ' + output);
sys.print('erroutput: ' + erroutput);
});
。。。但這隻是高層介面,該介面緩存所有的輸出等。 你可以獲得更多流行比如果你喜歡。
NodeJs將asynchronicity作為正常狀況,因此如果需要" 傳統" shell腳本,你可能會發現很不好,因為它不匹配( 在撰寫本文時,據我所知) 提供的同步版本 exec. 所以臨時一系列串列語句成為政黨政治回調:exec('first_command', function(error) {
if (error != null) {
exec('second_command', function(error) {
if (error != null) {
// ....
}
});
}
});
...但當然,可以為你創建的函數可以處理和接受( 說) 的數組順序執行的語句( 然後安裝它作為模塊通過Node是模塊sysstem ) 。 下面舉個實例:#!/usr/local/bin/node
var sys = require('sys'),
exec = require('child_process').exec;
execSeries([
'ls -ld /usr',
'foobar',
'ls -ld /etc'
], {echo: true}, function(results) {
sys.print("Donen");
});
// ===> This would be in a module, not in the script itself <===
function execSeries(series, options, callback) {
var index = 0,
results = [];
// Make 'options' optional
if (!callback && typeof options === "function") {
callback = options;
options = undefined;
}
// Default options
options = options || {};
// Go
callNext();
function callNext() {
if (index >= series.length) {
// Done
callback(results);
}
else {
// Call the next one
exec(series[index++], function(error, stdout, stderr) {
// Record result
results.push({error: error, stdout: stdout, stderr: stderr});
// Echo?
if (options.echo) {
if (error == null) {
sys.print(stdout);
}
else {
sys.print("Error: " + error + "n");
}
}
// Stop on error?
if (options.breakOnError && error != null) {
// Yes, and there was an error; stop
callback(results);
}
else {
// No, continue
callNext();
}
});
}
}
}