There is a local server. If you write 127.0.0.1/?com=ls in the request, then the ls should be executed in the terminal. I managed to transfer info from ls to the server, but it is displayed only to the console. Why console.log(ls) work, and response.write(ls) doesn't?

 var url = require("url"), http = require('http'), process = require('child_process'), qs = require("querystring"), fs = require('fs'), port = 8080; var server = http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/html"}); var query = url.parse(request.url).query; params = qs.parse(query); if(params.com=='ls'){ process.exec('ls', function(err, ls){ console.log(ls); response.write(ls); }); } response.end(); }); server.listen(port); console.log('Browse to http://127.0.0.1:' + port); 
  • one
    Because asynnchrony. You first work out responce.end(); and only after that the callback is called. But at this moment an attempt to call responce.write() will not lead to anything good. - Yaant
  • How to fix it? - Vitali
  • one
    In this case, it will be enough to move the call to responce.end() inside the callback. - Yaant

1 answer 1

After response.end() method will not work and node.js will "swear" to it, but the server will not fall.

 if (params.com === 'ls') { process.exec('ls', function(err, ls){ console.log(ls); response.write(ls); }); } response.end(); 

In your case, response.end() is called first.

Since you are invoking the ls command , then most likely you can get a response in parts and simply transfer response.end to callback instead of response.write will not be competent.

I would do as follows:

 if (params.com === 'ls') { process.exec('ls', function(err, data){ console.log(data); response.write(data); }).on('close', function () { // Всё прошло успешно. Все клиенту уже передали. // Может просто закрыть соединение. response.end(); }).on('error', function (err) { // обработка ошибки // и закрытие соединения console.log(err); response.end(); }) } 

One addition:

It is not necessary child_proccess refer to child_proccess as process , since such an object is already on global . And there are a lot of useful methods and variables in it. Very often take a separate method of this module, for example, as in your case, exec and already use it.

And it will look like this:

var exec = require('child_process').exec;