2017-02-16 94 views
-1

我不知道該怎麼問,但我想在Windows 10上運行'bash'命令,以便稍後運行一些linux命令。我正在使用框架Electron和Child Process。如何在Windows上運行linux終端命令?

var os = require('os') 
var exec = require('child_process').exec 
if (os.platform() =='win32'){ 
    var cmd_win = 'bash' 
    exec(cmd_win, function(error, stdout, stderr){ 
     console.log(error) 
    }); 
} 

該代碼片段給出「錯誤:命令失敗:bash」。有誰知道爲什麼?你能幫我嗎?我希望你能理解我的問題。

回答

-1

默認情況下,exec將使用cmd.exe在Windows中執行命令。您可能要查找的是the docs中指定的shell選項。

shell Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.)

const os = require('os') 
const exec = require('child_process').exec 

if (os.platform() === 'win32') { 
    exec('ls', {shell: 'path/to/executable.exe'}, (err, stdout, stderr) => { 
    if (err) { 
     console.error(err) 
     return 
    } 

    console.log(stdout) 
    }) 
} 
+0

OP的目的是在沒有參數的情況下啓動'bash.exe' _itself,(如果我理解正確的話,在後臺啓動它以初始化WSL子系統),而不是將_commands_傳遞給​​它,所以原則上默認的shell('cmd')應該沒問題,應該使用稍微高效的'execFile()'。 但是,這兩種方法都不能用於這個特定的可執行文件('bash.exe')。 – mklement0

1

要初始化WSL子系統,您必須在後臺,如果執行bash.exe直接不工作啓動(隱藏)猛砸控制檯窗口- 它與既沒有exec也沒有execFile

訣竅是讓殼(cmd)的過程,Node.js的滋生推出bash.exe無阻塞,而不幸的,是不容易的事:start不能使用,因爲bash.exe控制檯申請並因此使得start同步

解決方案是創建一個輔助。 VBScript文件啓動bash.exe,它本身可以通過wscript.exe異步調用。需要注意的是Bash的控制檯窗口啓動隱藏

var os = require('os') 
var exec = require('child_process').exec 
if (os.platform() === 'win32') { 
    var cmd_win = '\ 
    echo WScript.CreateObject("Shell.Application").\ 
     ShellExecute "bash", "", "", "open", 0 > %temp%\launchBashHidden.vbs \ 
    & wscript %temp%\launchBashHidden.vbs' 
    exec(cmd_win, function(error, stdout, stderr){ 
     if (error) console.error(error) 
    }); 
} 

注意,AUX。 VBScript文件%temp%\launchBashHidden.vbs在調用之間徘徊。每次運行後清理它需要更多的工作(你不能馬上刪除它,因爲wscript,由於異步運行,可能還沒有加載它)。