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

标签 node.js windows git-bash

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

无效路径示例 c:/程序文件/git/usr/bin/bash c:/程序\文件/git/usr/bin/bash /c/程序\文件/git/usr/bin/bash c:\\程序文件\\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

最佳答案

这种方法存在一些问题。

作为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 不需要使用自定义 shell;这是由 Git 可执行文件处理的。

关于node.js - 如何为 child_process.exec 指定 shell 可执行文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52525477/

相关文章:

javascript - 使用 Quill 进行 socket.io 富文本编辑

javascript - 在 MongoDB 查询中使用 javascript 变量作为 $regex 的值

python - 为什么在我的 Windows 机器上,我必须将命令写为 "py -m pip install "模块名”而不是只写 "pip install "模块名”?

node.js - 带有身份验证错误的 MongoDB Atlas 集群连接问题

git - 为什么github允许无法识别的作者提交

node.js - 我可以通过身份验证与 HAProxy 和 socket.io 进行粘性 session 吗?

node.js - Bluebird - promisification - promisifyAll of 'email-templates' Node 模块 - 发送邮件

python - 打开python最小化或隐藏的程序

java - 为什么 SimpleDateFormat 不能在 Mac OS X 10.6.5 上运行?

git 推送的文件不会显示在 cPanel 文件管理器中