kaushalpranav
kaushalpranav

Reputation: 2214

Getting the continuous output of another program in a string in Node JS

I have a program p1.exe that is continuously generating data (assume prime numbers) and prints in the console. I need to run a node program, that runs p1.exe inside it and we need to read all the data(here prime numbers) continuously, add 1 to each of it and print to the console in the Node JS program. This is not a homework problem.

Upvotes: 0

Views: 588

Answers (1)

AngYC
AngYC

Reputation: 3923

This should work, you can understand more from https://nodejs.org/api/child_process.html

const { spawn } = require('child_process');

function runAndGetPrimes(cb) {
    var exe = spawn("p1.exe"),
        output = "";

    exe.stdout.on('data', (data) => {
        output += data.toString();
    });
    exe.stderr.on('data', (data) => { });

    exe.on('close', (code) => {
        cb(output.split(" "));
    });
}

runAndGetPrimes((primes) => {
    primes.forEach((p) => {
        console.log(parseInt(p, 10) + 1);
    });
});

Upvotes: 2

Related Questions