0

Trying to execute shell command(any) from the browser and printing the result on the Ui using child_process.

unable to fetch the results from command line asynchronously.Am I missing something here ?

   const exec = require('child_process').exec;
    app.post('/plan',(req, res) => {

      let cmd = exec('dir');
      let output = "";
      cmd.stdout.on('data', (data) => {
        //console.log(`stderr: ${data}`);
        output += data;
       });
      res.send(output);                          //not working
      console.log(output);                       //its empty
      cmd.stderr.on('data', (data) => {
          console.log(`stderr: ${data}`);
       });
      cmd.on('close', (code) => {
         console.log(`child process exited with code ${code}`);
      });

    });
0

1 Answer 1

1

The shell command runs asynchronously. You need to send the response from within the callback function so that it sends the result when it is finished executing.

  cmd.stdout.on('data', (data) => {
    output += data;
    res.send(output); 
   });

Might be cleaner to do it like this:

const exec = require('child_process').exec;
app.post('/plan',(req, res) => {
  exec('dir', (error, stdout, stderr) => {
    if (error) {
      res.status(500).send(stderr);
      return;
    }
    res.send(stdout);
  });
});
Sign up to request clarification or add additional context in comments.

2 Comments

how do i access the stdout on ui ? the result which im recieving is body: (...) bodyUsed: false headers: Headers {} ok: true redirected: false status: 200 statusText: "OK" type: "basic" url: "http://localhost:3000/plan" __proto__: Response
You need to read the response stream as text developer.mozilla.org/en-US/docs/Web/API/Response. Try fetch('http://localhost:3000/plan').then(response => response.text()).then(console.log)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.