【问题标题】:How to run multiline commands in NodeJS with child_process.exec如何使用 child_process.exec 在 NodeJS 中运行多行命令
【发布时间】:2021-06-01 00:45:32
【问题描述】:

注意:this question 没有帮助我。

我正在尝试为Atom 创建一个任务运行程序,并且已经到了运行多行 shell 脚本的地步。但是

const child_process = require("child_process");
child_process.exec(
    `rm -rf something
         another
         directory`,
    (error, stdout, stderr) => {
        /*...*/
    },
)

导致节点认为anotherdirectory 是命令。

【问题讨论】:

    标签: javascript node.js child-process


    【解决方案1】:

    对我有用的是

    child_process.exec(
        yourCommand.replace((/\n/g, "\\\n"),
        (error, stdout, stderr) => {
            /*...*/
        },
    )
    

    这会将所有换行符修改为在换行符之前有一个反斜杠。


    对于 Windows,这将非常相似,但将所有新行替换为 ^\n 而不是 \\\n

    child_process.exec(
        yourCommand.replace((/\n/g, "^\n"),
        (error, stdout, stderr) => {
            /*...*/
        },
    )
    

    【讨论】:

    • 没错,在 Windows 上不起作用,但在 unix 上很好。你有什么想法,如何在 Windows 上解决这个问题?
    • 根据this question,在我看来你可以在Windows上做yourCommand.replace((/\n/g, "^\n")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 2020-02-14
    • 2020-05-20
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多