【问题标题】:How to pass parameters to bash command in node exec function?如何在节点 exec 函数中将参数传递给 bash 命令?
【发布时间】:2015-12-17 23:11:27
【问题描述】:

我想在节点 js child_process.exec() 中运行带有参数的 bash 脚本

在文档中是String The command to run, with space-separated arguments,但是

child.exec("cat path_to_file1 path_to_file2") 

不起作用。内部改为

/bin/sh -c cat path_to_file1 path_to_file2

失败了。我怎样才能正确运行它?在 shell 中我会这样修复它

/bin/sh -c 'cat path_to_file1 path_to_file2'

(我没有写回调,因为我只问命令参数)

【问题讨论】:

  • 不确定我是否理解您的问题。 exec("cat file1 file2") 工作正常。

标签: node.js child-process electron


【解决方案1】:

使用 exec 的 shell 选项:

child.exec("cat path_to_file1 path_to_file2", {
 shell : '/bin/bash' 
})

查看选项:https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

【讨论】:

  • 可以,但可以更新。所以,你用 shell 选项强制 shell。
【解决方案2】:

你尝试过这样的事情吗?

var exec = require('child_process').exec;
var child;
child = exec("cat '/route/to/file_a' '/route/to/file_b'", function (error, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
    if (error !== null) {
        console.log('exec error: ' + error);
    }
});

这样您就可以找出问题所在或得到正确的输出。 ;)

【讨论】:

    猜你喜欢
    • 2018-02-13
    • 2020-07-30
    • 1970-01-01
    • 2021-11-25
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    相关资源
    最近更新 更多