2

I want to run some predefined shell commands and return them as plain text in a http server. The content written at (1) is being served to my browser, but the content at (2) which eventually has to be the stdout is not being served. Can anybody help me how to achieve this?

var http = require('http'),
url = require('url'),
exec = require('child_process').exec,
child,
poort = 8088;


http.createServer(function(req, res) {
 res.writeHead(200, {'Content-Type': 'text/plain'});

    var pathname = url.parse(req.url).pathname;
    if (pathname == '/who'){
        res.write('Who:'); // 1
        child = exec('who',
                     function(error, stdout, stderr){
                        res.write('sdfsdfs');   //2
                     })


    } else {
        res.write('operation not allowed');
    }

 res.end();

}).listen(poort);

1 Answer 1

2

It's because of where you place res.end().

Since exec is asynchronous, res.end() actually happens before the res.write you label as (2). No more writes can be issued after an .end, so the browser doesn't get any further data.

You should call res.end() inside the exec callback, after res.write. The exec callback will be issued when the child process terminates and will get the complete output.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah bull*cks. Thank you, I struggled for like an hour with it. Completely forgetting the reason I choose node.js: the asynchronous behaviour :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.