2

I have a node.js script and a java program in the same folder (.class and .java and .js). I want to call the java program from the node.js script. In terminal I can call the java program like this

java -cp java-json.jar:. PlutoMake "tests/android.png"

I saw this thread How to call Java program from NodeJs

and I am trying to do the same thing, here is the node.js code

var child = spawn('java', ['-cp java-json.jar:. PlutoMake', 'tests/android.png']);

This seems to run without crashing, but then nothing happens. The java program creates an image, but if I do it through node, it doesn't work. Does anyone know whats wrong?

Thanks

0

2 Answers 2

6

The array of arguments you pass should have one element per argument. You’re incorrectly combining a few of them.

var child = spawn('java', ['-cp', 'java-json.jar:.', 'PlutoMake', 'tests/android.png']);

Checking the output and exit code could prove useful:

child.on('close', function (exitCode) {
    if (exitCode !== 0) {
        console.error('Something went wrong!');
    }
});

// If you’re really just passing it through, though, pass {stdio: 'inherit'}
// to child_process.spawn instead.
child.stderr.on('data', function (data) {
    process.stderr.write(data);
});
Sign up to request clarification or add additional context in comments.

9 Comments

That worked, thanks, but now how can I set an event that runs when the java script exits or finishes?
@sneaky: I edited the answer to write about checking the exit code for errors, but that’s also the event you’d use to continue (after confirming that the exit code was 0).
In java I know I can do like system.exit(0) and I think that triggers the first function above. Which one triggers when the java finishes executing (without calling exit and without throwing exception)? And also how does the second function above get triggered?
@sneaky: 0 is success. It is the default exit code. You don’t have to call system.exit for this to work. The second event is fired when there’s error output from the child process.
In my usecase I used Node.js as a tool which just needed to call some Java utility and wait for answer. In such case execFileSync is more suitable than spawn (also the method returned stdout as Node.js Buffer which had to be converted into string).
|
0

You can simply call a java command , with classpath & arguments, using module node-java-caller, it embeds the call to spawn and will also automatically install java if not present on the system

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.