Node.js不显示HTML文件的内容

时间:2014-10-28 05:54:29

标签: html node.js

我的代码是:

var http = require('http'),
url = require('url'),
fs = require('fs');

var handleRequest = function(request, response) {
console.log("Request received: " + request.url);
var path = url.parse(request.url).pathname;

switch(path){
    case '/':
        response.writeHead(200, {"Content-Type": "text/html"});
        response.write("<h1>Hello there!</h1>");
        break;

    case '/socket.html':
        console.log(__dirname + path);
        fs.readFile(__dirname + path, function(error, data){
                console.log(data);
                if (error){
                    response.writeHead(404);
                    response.write("This page doesn't exist");
                }
                else{
                    response.writeHead(200, {"Content-Type": "text/html"});
                    response.write(data, "utf8");
                }
            });
        break;

    default:
        response.writeHead(404);
        response.write("This page doesn't exist");
        break;
}
response.end();
};

var server = http.createServer(handleRequest);

server.listen(3000, "localhost", function() {
    console.log("Listening to port 3000...")
});

HTML文件与此文件位于同一目录中。它包含的只是一个简单的段落。页面加载但是空白。当我在console.log(数据)时,它会显示像Buffer 3c 21 44 ....等等。我做错了什么?感谢。

1 个答案:

答案 0 :(得分:0)

您在启动异步,非阻塞readFile()任务后立即结束响应。试试这个:

switch(path) {
  case '/':
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write("<h1>Hello there!</h1>");
    break;

  case '/socket.html':
    fs.readFile(__dirname + path, function(error, data) {
      if (error) {
        response.writeHead(404);
        response.write("This page doesn't exist");
      } else {
        response.writeHead(200, {"Content-Type": "text/html"});
        response.write(data);
      }
      response.end();
    });
    return;

  default:
    response.writeHead(404);
    response.write("This page doesn't exist");
    break;
}

response.end();

此外,您可能会考虑使用流将文件从磁盘传输到响应,以避免首先在内存中缓冲整个文件。