noob:node.js writeHead停止我的代码

好吧,我是Node.js的新手,所以请原谅这个问题。 下面是我的简单代码:

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'); 

现在,当我在terminal中运行脚本时,它将正确启动服务器,但是当我在我的浏览器(chrome)中访问我的localhost:8000时,它显示为“网页不可用”。

如果我注释掉writeHead命令,它工作正常。

为什么?

这是因为你正试图在.write()之后的.writeHead() .write()

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

.writeHead()必须是第一个:

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