2015-06-01 48 views
0

我試圖調用從節點JS多個系統調用JS節點

我的代碼片斷多個系統調用:

var sys = require('sys') 
var exec = require('child_process').exec;       
function puts(error, stdout, stderr) { sys.puts(stdout) }            
exec("rfkill block bluetooth ; rfkill unblock bluetooth ; hciconfig hci0 down ; hciconfig hci0 up", puts); 
console.log('BLE intialization DONE'); 

但那些沒有effect.if我通過一個在執行這些一個(即編輯文件,然後把命令一個接一個地執行)它正在工作。讓我知道是否有人可以爲此提出建議和解決方法。

編輯:或者是有其中多個系統調用可以陸續

回答

1

節點12來完成一個任何例子用於腳本目的synchronous child process execution interface

同步進程創建

這些方法是同步,這意味着它們將阻止事件循環,暫停代碼的執行,直到生成的進程退出。

阻止這樣的調用對於簡化通用腳本任務以及簡化啓動時加載/處理應用程序配置非常有用。

StrongLoop有介紹using it for scripting

var history = child_process.execSync('git log', { encoding: 'utf8' }); 
process.stdout.write(history); 

在你的情況,你應該檢查每個命令的錯誤(假設你關心他們),並做出適當的反應:

var shellCommands = ['rfkill block bluetooth', 'rfkill unblock bluetooth', 'hciconfig hci0 down', 'hciconfig hci0 up']; 
shellCommands.forEach(function(command) { 
    var execResponse = child_process.execSync(command, { encoding: 'utf8' }); 
    // if execResponse is non-zero, an error will be thrown here 
    // if you want to continue, you should handle it with try/catch 
    process.stdout.write(history); 
}); 
0

我不知道爲什麼你的代碼不工作。我有很多命令串在一起,就像你在我正在處理的代碼中的多個地方一樣,它工作得很好。我認爲你可能會看到的是,你的輸出語句console.log('BLE initialization DONE')愚弄你,認爲你的執行完全沒有完成。執行程序與您使用它的方式是異步的,所以您不會等到顯示輸出消息之前完成它。

相反,試試這個:

var sCommand = "rfkill block bluetooth ; rfkill unblock bluetooth ; hciconfig hci0 down ; hciconfig hci0 up"; 

exec(sCommand, function (error, stdout, stderr) { 
    console.log("error: ", error); 
    console.log("stdout: ", stdout); 
    console.log("stderr: ", stderr); 

    console.log('BLE initialization DONE'); 
    puts(error, stdout, stderr); 
    });