4

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.

2
  • 1
    May be less fragile to add a web service over the existing Java code and call that from node.js Commented Jan 28, 2013 at 16:25
  • Aha, excellent point, even if it were native Node.js it would be good to separate that out. Commented Jan 29, 2013 at 3:38

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the fast reply! Yes, calling child_process.exec() is ideal, and piping straight back even better. My uncertainty is whether java VM is installed, and if it can run a class/library I provide?
@user645715 I haven't checked, but I don't think a Java runtime is installed when node.js applications are installed. You'd either have to make you java app a stand-alone executable, push the Java runtime with your app or for and modify the buildpack to include a Java runtime.
Long delayed followup, Java appears installed by default in Heroku Cedar stack, and calling via shell worked very well.

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.