使用shell选项将bash与Node.js child_process一起使用失败 [英] Using bash with Node.js child_process using the shell option fails

查看:38
本文介绍了使用shell选项将bash与Node.js child_process一起使用失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

子进程api 可用于在node.js中执行shell脚本.

The child process api can be used to execute shell script in node.js.

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

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

as an option the user of exec can set the shell: '/path/to/shell' field to select the shell to be used. (Defaults to '/bin/sh')

将选项设置为{shell:'/bin/bash'}不会使exec用bash破坏命令.

我已经通过发出显示"/bin/sh"的命令"echo $ 0"来验证了这一点.

I have verified this by issuing the command "echo $0" which prints "/bin/sh".

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

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

(My goal is to make use of my path definitions in bashrc, now when i try to use grunt the binary cannot be found. Setting the cwd, current working directory in the options dictionary works as expected)

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

----------------- UPDATE, example

'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

prints: /bin/bash

推荐答案

可能在您的设置中,或者在代码中错误地传递了选项.由于您没有发布代码,因此很难分辨.但是我能够执行以下操作,并且可以正常工作(使用节点4.1.1):

Might be in your setup or passing options incorrectly in your code. Since you didn't post your code, it's tricky to tell. But I was able to do the following and it worked (using 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没有.我希望这会有所帮助!

I used time as the command since it's one that bash has and sh does not. I hope this helps!

这篇关于使用shell选项将bash与Node.js child_process一起使用失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆