2016-09-06 20 views
10

Sử dụng mô-đun child_process của Node, tôi muốn thực hiện lệnh thông qua trình bao Cygwin. Đây là những gì tôi đang cố gắng:Thực thi lệnh cygwin từ NodeJS

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) 

tôi có thể thấy Node's child_process.js will add the /s and /c switches, không phụ thuộc vào shell tùy chọn được thiết lập, bash.exe không biết phải làm gì với những lập luận này.

Tôi tìm thấy một công việc xung quanh cho vấn đề này nhưng nó thực sự không lý tưởng:

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

Làm ở trên sẽ rõ ràng chỉ làm việc trên Windows không hệ thống unix.

Làm cách nào để thực hiện các lệnh trong trình bao Cygwin từ NodeJS?

Trả lời

2

Đây không phải là giải pháp chung hoàn chỉnh, vì sẽ cần phải thực hiện thêm một số tùy chọn exec(), nhưng điều này sẽ cho phép bạn viết mã sẽ hoạt động trên Unix, Windows và Cygwin. hai.

Giải pháp này giả định rằng Cygwin được cài đặt trong một thư mục có tên bao gồm chuỗi 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); 
} 

Hoặc bạn có thể chiếm quyền điều khiển child_process.exec có điều kiện khi chạy trong Cygwin:

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) 
    } 
} 
Các vấn đề liên quan