Noob: node.js writeHead stopping my code

Ok, I'm new to Node.js, so sorry noob question. Here is my simple code:

var http = require('http'); var fs = require('fs'); // simple node.js server server = http.createServer(function (request, response){ var get_text = function (errors, contents){ response.write(contents); response.end('hello world'); } // get_text is the callback fs.readFile('log.txt', get_text); response.write('End of the callback'); response.writeHead(200); }); server.listen(8000); console.log('Server running at port 8000'); 

As I said, when I run the script in my terminal, it will start the server correctly, but when I go to my localhost: 8000 in my browser (chrome), it appears as "the web page is inaccessible".

If I comment on the writeHead command, it works fine.

Why?

+4
source share
1 answer

This is because you are trying to execute .writeHead() after .write() :

 response.write('End of the callback'); response.writeHead(200); 

.writeHead() should be the first:

 response.writeHead(200); response.write('End of the callback\n'); 
+3
source

Source: https://habr.com/ru/post/1493873/


All Articles