【问题标题】:Can'r run curl in nodejs with execFile可以使用 execFile 在 nodejs 中运行 curl
【发布时间】:2019-12-17 19:44:15
【问题描述】:

由于节点 exec 已弃用,我正在尝试将我的 nodejs 应用程序迁移到 execFile,但我遇到了 curl 调用的问题。

这是与 exec 合作的:

const pab_state = `/usr/bin/curl -d '{"jsonrpc": "2.0", "id": 1, "method": "core.playback.get_state"}' -H 'Content-Type: application/json' http://192.168.1.59:6680/mopidy/rpc`
child = exec(pab_state, (error, stdout, stderr) => {

尝试迁移到 execFile 我遇到了转义引号的问题:

const pab_args = ['-d \'{"jsonrpc": "2.0", "id": 1, "method": "core.playback.get_current_tl_track"}\'',' -H \'Content-Type: application/json\'',' http://192.168.1.59:6680/mopidy/rpc'];

child = execFile("/usr/bin/curl",pab_args, (error, stdout, stderr) => {

这是我得到的错误:

{"killed":false,"code":3,"signal":null,"cmd":"/usr/bin/curl -d '{\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"core.playback.get_current_tl_track\"}'  -H 'Content-Type: application/json'  http://192.168.1.59:6680/mopidy/rpc"}

【问题讨论】:

    标签: node.js express curl


    【解决方案1】:

    options 参数中尝试指定shell,例如'/bin/bash'

    这是因为execFileexec 不同,默认情况下直接生成命令而不首先生成shell。这会导致curl 命令由于缺少外壳而无法正确执行。 解决此问题的方法是在 options 参数中指定要使用的 shell。

    这是一个例子,

    const { execFile } = require("child_process");
    
    const child = execFile(
      "/usr/bin/curl",
      [
        "-H 'Content-Type: application/json'",
        '-d \'{"title":"foo","body":"bar","userId":"1"}\'',
        "https://jsonplaceholder.typicode.com/posts "
      ],
      { shell: "/bin/bash" },
      function(error, stdout, stderr) {
        if (error) {
          throw error;
        }
        console.log(stdout);
      }
    );
    

    【讨论】:

    • 谢谢。我一回到家就试一试,告诉你。
    • @FabioMarzocca 很高兴它有帮助:)
    猜你喜欢
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 2015-06-27
    • 2020-06-12
    • 2022-08-14
    • 1970-01-01
    相关资源
    最近更新 更多