[英]Execute cygwin command from NodeJS
使用Node的child_process
模塊,我想通過cygwin shell執行命令。 這就是我正在嘗試的:
var exec = require('child_process').execSync;
exec('mkdir -p a/b/c', {shell : 'c:/cygwin64/bin/bash.exe -c'});
TypeError: invalid data at WriteStream.Socket.write (net.js:641:11) at execSync (child_process.js:503:20) at repl:1:1 at REPLServer.defaultEval (repl.js:262:27) at bound (domain.js:287:14) at REPLServer.runBound [as eval] (domain.js:300:12) at REPLServer. (repl.js:431:12) at emitOne (events.js:82:20) at REPLServer.emit (events.js:169:7) at REPLServer.Interface._onLine (readline.js:212:10)
我可以看到Node的child_process.js將添加/s
和/c
開關 ,無論是否設置了shell
選項,bash.exe都不知道如何處理這些參數。
我找到了解決這個問題的方法,但它真的不理想:
exec('c:/cygwin64/bin/bash.exe -c "mkdir -p a/b/c"');
執行上述操作顯然只適用於Windows而非unix系統。
如何從NodeJS在cygwin shell中執行命令?
這不是一個完整的通用解決方案,因為需要使用exec()
一些選項來完成更多,但這應該允許您編寫可以在unixes,Windows和cygwin上運行的代碼,區分后兩者。
此解決方案假定Cygwin安裝在名稱中包含字符串cygwin
的目錄中。
var child_process = require( 'child_process' )
, home = process.env.HOME
;
function exec( command, options, next ) {
if( /cygwin/.test( home ) ) {
command = home.replace( /(cygwin[0-9]*).*/, "$1" ) + "\\bin\\bash.exe -c '" + command.replace( /\\/g, '/' ).replace( /'/g, "\'" ) + "'";
}
child_process.exec( command, options, next );
}
你可以在Cygwin下運行時有條件地劫持child_process.exec:
var child_process = require( 'child_process' )
, home = process.env.HOME
;
if( /cygwin/.test( home ) ) {
var child_process_exec = child_process.exec
, bash = home.replace( /(cygwin[0-9]*).*/, "$1" ) + "\\bin\\bash.exe"
;
child_process.exec = function( command, options, next ) {
command = bash + " -c '" + command.replace( /\\/g, '/' ).replace( /'/g, "\'" ) + "'";
child_process_exec( command, options, next )
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.