I'm trying to run a NodeJS script from a Java application but I'm getting an error.
Java code:
ProcessBuilder pb = new ProcessBuilder("node --version");
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
Process p = pb.start();
Error:
Exception in thread "main" java.io.IOException: Cannot run program
"node --version": CreateProcess error=2, Unable to find the specified
file
I tried using the solutions from StackOwerflow
From official documentation of ProcessBuilder (Java SE 8):
ProcessBuilder
Each process builder manages these process attributes:
- a command, a list of strings which signifies the external program file to be invoked and its arguments, if any. Which string lists represent a valid operating system command is system-dependent. For example, it is common for each conceptual argument to be an element in this list, but there are operating systems where programs are expected to tokenize command line strings themselves - on such a system a Java implementation might require commands to contain exactly two elements.
That means that you should put each argument as a separate string in the list like this:
List<String> command = Arrays.asList("C:\\ProgramFiles\\nodejs\\node.exe", "--version");
ProcessBuilder builder = new ProcessBuilder(command);
/* configure your process builder as you need */