2016-04-13 158 views
6

我使用node.js v4.4.4,我需要從node.js運行.bat文件。如何執行從node.js傳遞一些參數的.bat文件?

從我的節點JS文件的位置應用程序中的蝙蝠是可運行的使用具有以下路徑(Window平臺)的命令行:

'../src/util/buildscripts/build.bat --profile ../profiles/app.profile.js' 

但是使用節點,當我不能運行它,沒有具體的錯誤被拋出。

我在這裏做錯了什麼?


var ls = spawn('cmd.exe', ['../src/util/buildscripts', 'build.bat', '--profile ../profiles/app.profile.js']); 

    ls.stdout.on('data', function (data) { 
     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); 
    }); 
+0

相關:https://nodejs.org/api/child_process.html#child_process_spawning_bat_and_cmd_files_on_windows – GibboK

+0

相關:https://medium.com/@graeme_boy/how-to-optimize-cpu-intensive-work-in-node-js-cdc09099ed41#.zbzjytwzw – GibboK

回答

8

下面的腳本解決了我的問題,基本上我只好:

  • 轉換爲絕對路徑引用到.bat文件。

  • 使用數組將參數傳遞給.bat。

    var bat = require.resolve('../src/util/buildscripts/build.bat'); 
    var profile = require.resolve('../profiles/app.profile.js'); 
    var ls = spawn(bat, ['--profile', profile]); 
    
    ls.stdout.on('data', function (data) { 
        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); 
    }); 
    

下面有用的相關文章的列表:

https://nodejs.org/api/child_process.html#child_process_asynchronous_process_creation

http://www.informit.com/articles/article.aspx?p=2266928

9

你應該能夠運行如下命令:

var child_process = require('child_process'); 

child_process.exec('path_to_your_executables', function(error, stdout, stderr) { 
    console.log(stdout); 
}); 
+0

我可以問你...你爲什麼使用.exec而不是產卵? – GibboK

+0

使用帶shell選項的spawn set與exec相同。文檔[這裏](https://nodejs.org/api/child_process.html#child_process_spawning_bat_and_cmd_files_on_windows) –

+0

你確定嗎?根據這個文檔,他們是不同的,我需要使用產卵,如果可能insd exec。你可以在你的答案上添加一個產卵解決方案? http://www.hacksparrow.com/difference-between-spawn-and-exec-of-node-js-child_process.html – GibboK

相關問題