简体   繁体   English

从NodeJS执行cygwin命令

[英]Execute cygwin command from NodeJS

Using Node's child_process module, I'd like to execute commands via the cygwin shell. 使用Node的child_process模块,我想通过cygwin shell执行命令。 This is what I'm trying: 这就是我正在尝试的:

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)

I can see Node's child_process.js will add the /s and /c switches , regardless of the shell option being set, bash.exe doesn't know what to do with these arguments. 我可以看到Node的child_process.js将添加/s/c开关 ,无论是否设置了shell选项,bash.exe都不知道如何处理这些参数。

I found a work around for this problem but it's really not ideal: 我找到了解决这个问题的方法,但它真的不理想:

exec('c:/cygwin64/bin/bash.exe -c "mkdir -p a/b/c"');

Doing the above would obviously only work on Windows not unix systems. 执行上述操作显然只适用于Windows而非unix系统。

How can I execute commands in the cygwin shell from NodeJS? 如何从NodeJS在cygwin shell中执行命令?

This is not a complete generic solution, because more would need to be done with some of the options of exec() , but this should allow you to write code that will work on unixes, Windows and cygwin, differentiating between the later two. 这不是一个完整的通用解决方案,因为需要使用exec()一些选项来完成更多,但这应该允许您编写可以在unixes,Windows和cygwin上运行的代码,区分后两者。

This solution assumes that Cygwin is installed in a directory which name includes the string 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 );
}

You could alternatively hijack child_process.exec conditionally when running under Cygwin: 你可以在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM