Search code examples
javanode.jsstreampipe

How to transmit data from Nodejs program to Java program?


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?


Solution

  • 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";