How to run multiline commands in NodeJS with child_process.exec

Viewed 746

NOTE: this question did not help me.

I'm trying to create a task runner for Atom and I've come to the point of running multi-line shell scripts. But

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

Lead to node to think that another and directory were commands.

1 Answers

What worked for me is

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

Which will modify all newlines to have a backslash before the newline.


For Windows, it would be very similar but replacing all new lines with ^\n instead of \\\n:

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