0

Inside the Java class is the following:

Process process = Runtime.getRuntime().exec("node /home/master/code/nodejs/searchLi.js");
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
    builder.append(line);
    builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
System.out.println(result);

Inside the nodejs searchLi is the following:

const Stream = require('stream');
const readableStream = new Stream.Readable();
readableStream.push('ping!');
readableStream.push('pong!');
console.log("success");
return "success";

As you can see I tried to implement streams but failed. How to transmit a String from the nodejs file to the Java file?

2 Answers 2

1

Your Java code is fine, but your node.js code isn't using streams properly. Either just stop using a stream of your own and just use process.stdout.write instead, or fix your streams to point there, like this:

const Stream = require('stream');
const readableStream = new Stream.Readable();
readableStream.push('ping!');
readableStream.push('pong!');
readableStream.push(null);
readableStream.pipe(process.stdout);
console.log("success");
return "success";
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for! Thank you!
0

You can setup a http server, although for something this small (a string) I suggest using the fs npm library to create a file and have the java program read from it.

I'm not experienced in java but I assume that there is a file reading library.

4 Comments

Thank you for your answer! I was just wondering if it was possible to use the return value directly as you would with 2 files of the same language? Are the streams a viable option in your opinion?
Spawning an HTTP server to just to communicate between a parent and child process is quite frankly one of the most overcomplicated solutions I've ever heard.
@JosephSible-ReinstateMonica I'm not proficient in this kind of stuff, and I didn't suggest that as the solution.
@propre_poli streams are definetely what you should use, the other answer gives you a good solution. I looked through streams and it seems like it uses my file solution's flow but optimizes it.

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.