Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send output of shell command to client in Node.js

I'd like to send output of shell command to client.

Here is the code snippet which handles POST request:

app.post('/', function(req, res) {

    console.log("request is received");
    const ps = spawn('sh', ['test.sh', req.body.code]);
    ps.stdout.on('data', (data) => {
        console.log(`stdout: ${data}`);
    });

    ps.stderr.on('data', (data) => {
        console.log(`stderr: ${data}`);
    });

    ps.on('close', (code) => {
        console.log(`child process exited with code ${code}`);
    });

    // echo incoming data to test whether POST request works
    res.status(200).json({ myReply: req.body.code });

});

How can I send stdout to client in such a case?

like image 351
yildizabdullah Avatar asked Jan 01 '26 00:01

yildizabdullah


1 Answers

You can stream the stdout from the child process back to res. This works because ps.stdout is a readable stream and res is a writable stream.

ps.stdout.pipe(res)
like image 168
ralphtheninja Avatar answered Jan 06 '26 10:01

ralphtheninja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!