简体   繁体   中英

Pass more dynamic run time arguments to NodeJS child process

I want to run a Java program using NodeJS child process.

const util = require('util');
const exec = util.promisify(require('child_process').exec);

let dir = `${__dirname}/runtime/java/main`;

await exec(`javac Test.java`, {cwd: dir});
const { stdout, stderr } = await exec(`java Test`, {cwd: dir});

My Java code is taking multiple scanner run time arguments dynamically:

import java.util.Scanner; 

class Test {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);  
    System.out.println("Enter number of test cases");

    int count = scanner.nextInt();  
    for(int i=0; i<count; i++){
      String testCaseDescription = scanner.nextLine();  
      System.out.println("Test case " + i + " is "+testCaseDescription);  
    }

  }
}

How do I pass dynamic run-time parameters to the child process?

As per the documentation of child_process.exec() , the first parameter given to the function is "the command to run, with space-separated arguments".

So, we need to get the command line arguments given to your Node.js script and pass them along to exec() . In Node.js, we can get these arguments via the process.argv property (more about it here ).

process.argv is an array, and you will want to exclude the first element (which is the path of the Node.js runtime executing your file) as well as the second element (which is the path to your Node.js script). You can use the slice() method to get only the portion of the array you want.

Then, you will want to transform the array (minus the first two elements) in a space-separated string. You can do this by using the join() method .

The final result would look like this:

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function run() {
    const dir = `${__dirname}/runtime/java/main`;
    await exec(`javac Test.java`, {cwd: dir});

    // Transforming the CLI arguments into a comma-separated string
    const cliArguments = process.argv.slice(2).join(' ');
    // Executing and passing the CLI arguments
    const { stdout, stderr } = await exec(`java Test ${cliArguments}`, {cwd: dir});
}

run();

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