3

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?

2 Answers 2

3

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) 
Sign up to request clarification or add additional context in comments.

2 Comments

This only pipes stdout, not both stdout and stderr
So you add ps.stderr.pipe(res). However, the question specifically asks for stdout at the bottom.
1

First it should be noted that what you about to do is dangerous. Very dangerous.

Blindly executing a command from a client is not wise, you should sanitize both your ingress and egress data from untrusted sources.

While I am indeed making an assumption that this is not happening based on your provided example I just firmly believe you should rethink your design if this is the case.

Now that I have spoken up you should capture stdout to any array or object during the on('data', (data) => { and send it to the client on close.

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

ps.stderr.on('data', (data) => { console.log(`stderr: ${data}`); }); ps.on('close', (code) => { console.log(`child process exited with code ${code}`); res.status(200).json(results); }); // echo incoming data to test whether POST request works res.status(200).json({ myReply: req.body.code });` 

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.