如何为child_process.exec指定shell可执行文件?

时间:2018-09-26 20:17:25

标签: node.js windows git-bash

我在Windows 10中使用GitBash,并希望在child_process.exec调用中执行git命令。我认为,由于我是通过“ Git For Windows”安装git的,因此只需要将shell指定为GitBash可执行文件即可。我已经尝试过可以想到的GitBash可执行文件路径的所有变体,但总会失败。节点正在寻找的路径是什么?

不起作用的路径示例 c:/program files/git/usr/bin/bash c:/program\ files/git/usr/bin/bash /c/program\ files/git/usr/bin/bash c:\\program files\\git\\usr\\bin\\bash

const { expect } = require('chai');
const { exec } = require('child_process');

describe.only('exec', function(){
    it('should work', function(done){
        let shellPath = "c:\\program files\\git\\usr\\bin\\bash";
        expect(exec(`cat <<< "abc"`, { shell: shellPath }, (err, stdout) => {
            expect(err).to.be.null;
            expect(stdout.trim()).to.be.equal("abc");
            done();
        }));
    });
});

第一个断言失败:

expected [Error: Command failed: cat <<< "abc" << was unexpected at this time.] to be null

1 个答案:

答案 0 :(得分:1)

这种方法存在一些问题。

the reference指出,exec automatically uses Windows-specific shell arguments不适用于Bash。

另一个问题是PATH可能未设置为GitBash二进制路径。

这可能应该起作用:

delete process.platform;
process.platform = 'linux';

exec(`cat <<< "abc"`, {
  env: { PATH: 'C:\\Program Files\\git\\usr\\bin' },
  shell: 'C:\\Program Files\\git\\usr\\bin\\bash.exe'
}, (err, stdout) => {
  ...
});

process.platform = 'win32';

此解决方案的可操作性可能取决于bash.exe的实现。

在Node中运行git不需要使用自定义外壳程序;这是由Git可执行文件处理的。