node.js - 如何为 child_process.exec 指定 shell 可执行文件?
问题描述
我在 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
解决方案
这种方法存在一些问题。
如参考所述,自动使用不适用于 Bashexec
的特定于 Windows 的 shell 参数。
另一个问题是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
实施。
git
在 Node中运行不需要使用自定义 shell ;这是由 Git 可执行文件处理的。
推荐阅读
- sas - SAS:提高交叉连接的效率
- javascript - 动态加载精灵 SVG 文件
- c# - c#切片特定字符的字符串索引
- postgresql - 无法使用 Golang Gorm 连接到 RDS Postgres
- javascript - 下拉项目的日期显示为 NAN,但单元格的日期显示为 NAN
- c# - 如何在另一个类中的属性更改后调用方法?
- android-studio - Android Studio 预览未显示 ActionBar
- ansible - Molecule 是如何进行角色查找的
- gcc - 我怎样才能让LD始终将入口点放在-Ttext的位置?
- dart - 使用 badCertificateCallback - http-package 接受自签名证书