使用bash和Node.js的child_process使用shell选项失败
subprocessAPI可以用来在node.js中执行shell脚本。
我使用child_process.exec(命令[,选项],callback)函数
作为一个选项,exec的用户可以设置shell:'/ path / to / shell'来select要使用的shell。 (默认为'/ bin / sh')
将选项设置为{shell:'/ bin / bash'}不会使exec用bash命令。
我已经通过发出打印“/ bin / sh”的命令“echo $ 0”来validation这一点。
如何通过shell选项使用bash和child_process.exec?
(我的目标是在bashrc中使用我的path定义,现在当我尝试使用grunt时,无法find二进制文件。设置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
可能在您的代码中错误地设置或传递选项。 既然你没有发布你的代码,这很难说。 但是我能够做到以下几点,它工作(使用节点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不是。 我希望这有帮助!