代码之家  ›  专栏  ›  技术社区  ›  Todd

如何为child\u process.exec指定shell可执行文件?

  •  0
  • Todd  · 技术社区  · 6 年前

    我在Windows10中使用GitBash,希望在child\u process.exec调用中执行git命令。我想既然我是通过“gitforwindows”安装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 回复  |  直到 6 年前
        1
  •  3
  •   Estus Flask    6 年前

    这种方法有一些问题。

    作为 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

    运行时不需要使用自定义shell git 在节点中;这是由Git可执行文件处理的。