简体   繁体   中英

How to pass parameters from exec method to batch file using NodeJS

I am creating a child process in nodejs where it will compile and execute the java code. Below is the code

const exec = require('child_process').exec;  
    exec('C:/Development/vilearn/vilearn_node/src/my.bat', (err, stdout, stderr) => {  
      if (err) {  
        console.error(err);  
        return;  
      }  
      console.log(stdout);  
    });  

How can i pass the parameters from exec method to batch file. Below is my batch file.

set path=C:\Program Files\Java\jdk1.8.0_111\bin
cd C:\Development\vilearn\vilearn_node\src
pwd
javac Hello.java
java Hello

As you can see from the above code i am using this batch file to compile the java code. Here i want to pass the path where java file exists and also the name of the java file from exec method so that it will b dynamic.

Please guide me

Help Appreciated!

Use '%*' to select all parameters or '%1', '%2', ... to select a specific one

And use ' spawn ' to load the batch then pass the params on the second param as an array of strings

You may pass parameters from the nodejs script like this,

const exec = require('child_process').exec;
const param1 = 'Hello.java';
const param2 = 'Hello';

exec(`"C:/Development/vilearn/vilearn_node/src/my.bat" "${param1}" "${param2}"`, (err, stdout, stderr) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log(stdout);
});

in your bat file,

set path=C:\Program Files\Java\jdk1.8.0_111\bin
cd C:\Development\vilearn\vilearn_node\src
pwd
javac %1
java %2

Use double quotes on your parameters to avoid splinting from space as 2 parameters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM