prototype prototype - 3 months ago 11
Java Question

Execute Java program server-side from a Node.js / Heroku app?

Can I call a Java program from a Node.js application on Heroku?

I have a Node.js/Heroku app. But now need to add server-side capability to run an algorithm on an input data file and output data to a JSON format. I already have a Java library that can read the file and run the algorithm, and it would be very difficult (at best) for me to re-write it in pure Node.js.

So, could write a command line program, that takes an input file and pipes the results to stdout, e.g.

java mytask.class -cp ./mylibrary.jar --in /tmp/file.in > output.json


Is it possible to shell out a call to a Java command line program from Node.js? I know one can deploy Java applications to Heroku, but here want to execute a bit of Java from a Node.js app.

Answer

Don't you want this and child_process.exec() in particular ?

Node provides a tri-directional popen(3) facility through the child_process module.

It is possible to stream data through a child's stdin, stdout, and stderr in a fully non-blocking way.

Note that your example command above isn't right, since you're trying to pipe to a file (output.json). Pipes only work between processes. The child process module would allow you to read the processes' stdout directly and you wouldn't need the file (similarly for the input stream)

Comments