Search code examples
node.jswindowscommand-lineautomation

Run multiple windows commands from nodejs


When my windows server receives a post request, I need it to execute a command:

cd D:\project
git pull
mvn clean compile
cd target
java -jar app.jar -argument

I wrote the code, but it does not work:

const nodeCmd = require('node-cmd')

app.post((req, res) => {
  let command = `cd D:\project\my_project
                 git pull
                 mvn clean compile
                 cd target
                 java -jar app.jar ${req.body.arg}`;
  nodeCmd.get(command, (err, data, stderr) => {
    if(data) { 
     return res.json(data);
    }
    return err;
 });
})

Here is the error message:

{ Error: Command failed: cd D:projectmy_project && dir
The system cannot find the path specified.

    at ChildProcess.exithandler (child_process.js:294:12)
    at ChildProcess.emit (events.js:198:13)
    at maybeClose (internal/child_process.js:982:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
  killed: false,
  code: 1,
  signal: null,
  cmd: 'cd D:Tempautobooker && dir' }

Solution

  • The backslashes in your command string are not escaped. You can use string.raw to instruct the JS engine to treat a template literal as a raw string.

    let command = String.raw`cd D:\project\my_project
                             git pull
                             mvn clean compile
                             cd target
                             java -jar app.jar ${req.body.arg}`;