gpt4 book ai didi

node.js - 使用 shell 选项将 bash 与 Node.js child_process 一起使用失败

转载 作者:IT老高 更新时间:2023-10-28 23:26:04 28 4
gpt4 key购买 nike

child process api可用于在node.js中执行shell脚本。

我正在使用 child_process.exec(command[, options], callback) 函数

作为一个选项,exec 的用户可以设置 shell: '/path/to/shell' 字段来选择要使用的 shell。 (默认为“/bin/sh”)

将选项设置为 {shell: '/bin/bash'} 不会使 exec 使用 bash 运行命令。

我已经通过发出打印“/bin/sh”的命令“echo $0”验证了这一点。

如何通过 shell 选项将 bash 与 child_process.exec 一起使用?

(我的目标是在 bashrc 中使用我的路径定义,现在当我尝试使用 grunt 时找不到二进制文件。设置 cwd,选项字典中的当前工作目录按预期工作)

----------------- 更新,示例

'use strict';
var cp = require('child_process');
cp.exec('echo $0', { shell: '/bin/bash' }, function(err, stdout, stderr){
if(err){
console.log(err);
console.log(stderr);
}
console.log(stdout);
});

输出:

/bin/sh

which bash

打印: /bin/bash

最佳答案

可能在您的设置中或在您的代码中错误地传递了选项。由于您没有发布代码,因此很难判断。但我能够执行以下操作并且它有效(使用 Node 4.1.1):

"use strict";
const exec = require('child_process').exec

let child = exec('time',{shell: '/bin/bash'}, (err, stdout, stderr) => {
console.log('this is with bash',stdout, stderr)
})
let child2 = exec('time',{shell: '/bin/sh'}, (err, stdout, stderr) => {
console.log('This is with sh', stdout, stderr)
})

输出将是:

this is with bash  
real 0m0.000s
user 0m0.000s
sys 0m0.000s

This is with sh /bin/sh: 1: time: not found

我使用 time 作为命令,因为它是 bash 具有而 sh 没有的命令。我希望这会有所帮助!

关于node.js - 使用 shell 选项将 bash 与 Node.js child_process 一起使用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32952410/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com