【问题标题】:Why do nodejs exec/spawn not show any output for bash 'history' command?为什么 nodejs exec/spawn 不显示 bash 'history' 命令的任何输出?
【发布时间】:2020-04-25 22:15:16
【问题描述】:

我在 Ubuntu 上运行此程序,并尝试了许多 exec/spawn 函数(及其同步对应函数)的变体,但没有一个可以向我显示 bash 'history' 命令的输出。一种情况如下:

const { spawnSync} = require('child_process');
const child = spawnSync('history', { shell: "/bin/bash" });

console.log('error: ', child.error);
console.log('stdout: ', child.stdout.toString());
console.log('stderr: ', child.stderr);

它没有显示任何错误并且输出为空。我认为这个问题与历史命令的“专业”或类别有关,而不是 nodejs 的功能,因为它们对于 ls、pwd、whoami 等普通命令工作正常。我查看了我的 .bash_history 文件,其中充满了历史记录,所以这不是问题。

另一个可能类似的问题是ll 命令也会失败,即使我已将 bash 设置为 shell。但是对于ll,它确实返回了一个错误:

/bin/bash: ll: 找不到命令

为了确定,我尝试在 bash 中运行 ll 命令,它工作得很好。我在这里错过了什么?

编辑:我做了更多的测试,它看起来更像是一个 bash 的东西而不是一个节点的东西。当我简单地编写history 命令时,bash 会打印结果,但是当我执行bash -c history 时,它不会显示任何输出,也不会显示错误。

【问题讨论】:

    标签: node.js linux bash shell exec


    【解决方案1】:

    你需要订阅来自子进程的消息

     child.on('error', (err) => {
     });
    
     child.stderr.on('data', (data) => {
     });
    
     child.on('exit', (code, signal) => {
     });
    

    【讨论】:

    • 与我自己的代码相同的结果。除了您的代码之外,我还订阅了标准输出,但该结果从未用于历史命令。其他命令正在打印它们的结果就好了。会不会是 bash 而不是节点?
    猜你喜欢
    • 2021-02-24
    • 2021-05-26
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    相关资源
    最近更新 更多