DEV Community

vaibhav singh
vaibhav singh

Posted on

Send Shell script server output to react client

I'm new in MERN & I have a shell script to upload some data to mongodb,
from nodejs i have to execute shellscript and show it to client side in react like streaming.

i'm using child process ref. code below and getting the Events output on console.

But when requesting from React with axios.get() , i'm not getting event wise output, after complete processing, getting the complete output in the response.

const spawn = require('child_process').spaw;

const options = {shell: true,detached:true,}

res.writeHead(200, {'Content-Type': 'text/event-stream','Cache-Control': 'no-cache','Connection': 'keep-alive'});

var child = spawn(file.sh,[sort_name], options);

child.stdout.setEncoding('utf8');

child.stdout.on('data', function (data) {

res.write(data);

});

child.stderr.setEncoding('utf8');

child.stderr.on('data', function (data) {

res.write(data);

});

child.on('close', function (code) {

console.log('Full output of script');

res.end();

});

Top comments (3)

Collapse
 
failuree profile image
Avinash Srivastava

What you can do is create a web service, that you will call with your React JS application. This web service will execute the script directly on the server and when it's done you can return data to display on your React JS application.

Collapse
 
vaibbhav profile image
vaibhav singh

I have shared code ref. above, i need to show event listing on client side(React) not the complete result once.

Collapse
 
dance2die profile image
Sung M. Kim

Hi vaibhav. Can I request you to format the code snippet in the post by referring to the Editor Guide?

because people tend to help more when seeing highlighted code snippets