4

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 3

6

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();
Sign up to request clarification or add additional context in comments.

Comments

5

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

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
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");
1

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

Java 7 ProcessBuilder is even better. It allows piping: docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.