I am currently developing a Java system that communicates with node.js using socket.io. The system and the script are on the same server. How can I execute the script from my Java code and keep it alive from my app?
3 Answers
Note when using process builder the path to your JavaScript file is an argument and "node" is the command, so they need to be separated:
ProcessBuilder pb = new ProcessBuilder("node", "app.js");
This is also useful for inheriting its console output, starting the process and getting the reference to the process:
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
Process p = pb.start();
Comments
Say you have a node.js script named "mynodejs.js". You can use the following java code:
Process p = Runtime.getRuntime().exec("node mynodejs.js");
or
ProcessBuilder b = new ProcessBuilder("node mynodejs.js", "-args");
2 Comments
B. TIger
Im having problems executing these comands I always get an error saying that node is not a program but I dont get this error executing from the terminal is my app not reading the environment variables correctly
Calvin Zhang
Be sure your node.exe is in your system path or you may want to use something like this: Process p = Runtime.getRuntime().exec("C:\\Program Files\\nodejs\\node.exe mynodejs.js");
Have a look at ProcessBuilder class.
You can start any process on your machine like you would via shell, if I understand your question correctly.
1 Comment
Sotirios Delimanolis
Java 7 ProcessBuilder is even better. It allows piping: docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html