使用Node的child_process模块,我想通过cygwin shell执行命令.这就是我正在尝试的:
var exec = require('child_process').execSync;
exec('mkdir -p a/b/c', {shell : 'c:/cygwin64/bin/bash.exe -c'});
Run Code Online (Sandbox Code Playgroud)
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"');
Run Code Online (Sandbox Code Playgroud)
执行上述操作显然只适用于Windows而非unix系统.
如何从NodeJS在cygwin shell中执行命令?
这不是一个完整的通用解决方案,因为需要对 的一些选项进行更多操作exec(),但这应该允许您编写可在 unix、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 );
}
Run Code Online (Sandbox Code Playgroud)
您也可以在 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 )
}
}
Run Code Online (Sandbox Code Playgroud)