\$\begingroup\$
\$\endgroup\$
I'm reading Professional Node.js: Building Javascript Based Scalable Software by Pedro Teixeira and created a web page responding with www.google.de. Could you take a look at my code and let me know if the implementation is not good?
var request = require('request');
var url = 'http://www.google.de'; // input your url here
// use a timeout value of 10 seconds
var timeoutInMilliseconds = 10 * 10000;
var opts = {
url : url,
timeout : timeoutInMilliseconds
};
require('http').createServer(function(req, res) {
res.writeHead(200, {
'Content-Type' : 'text/html'
});
request(opts, function(err, webRes, body) {
if (err) {
console.dir(err);
return;
}
var statusCode = webRes.statusCode;
console.log('status code: ' + statusCode);
res.write(body);
});
}).listen(4000);
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Nov 24, 2013 at 8:17
1 Answer 1
\$\begingroup\$
\$\endgroup\$
Here are my suggestions:
- Get rid of the anonymous functions. They are notoriously difficult to test. I am hoping that you have written the test cases. If not, now would be a good time to try writing these tests.
- There is either a documentation or implementation bug where you want the timeout to be 10s (10000ms) but are actually using a value of
10*10000
ms which is 100s. - Rather than calling a method directly on
require('http')
, I'd like it if you import it the way you have importedrequest
. - You are always sending back a response code of 200. You should wait till after the request has finished fetching the page and set the status code accordingly unless you have some way of serving the right content (using a cahed copy, for example).
Other than that, I think that you have the actual functionality pretty much nailed down.
answered Nov 24, 2013 at 11:00
Explore related questions
See similar questions with these tags.
default