开发者

Node.js send static files such as HTML files

开发者 https://www.devze.com 2023-04-09 11:09 出处:网络
I\'m using the following script to show an html file in my browser: var sys = require(\"sys\"), http = require(\"http\"),

I'm using the following script to show an html file in my browser:

var sys = require("sys"),
    http = require("http"),  
    url = require("url"),  
    path = require("path"),  
    fs = require("fs");  

http.createServer(function(request, response) {
    var uri = url.parse(request.url).pathname;
    var filename = path.join(process.cwd(), uri);
    path.exists(filename, function(exists) {
        if (!exists) {
            response.sendHeader(404, {"Content-Type": "text/plain"});
            response.write("404 Not Found\n");
            response.close();
            return;
        }

        fs.readFile(filename, "binary", function(err, file) {
            if (err) {
                response.sendHeader(500, {"Content-Type": "text/plain"});
                response.write(err + "\n");
                response.close();
                return;
            }

            response.sendHeader(200);
            response.write(file, "binary");
            response.close();
        });  
    });  
}).listen(8080);  

sys.puts("Server running at http://localhost:8080/");  

But when I try to navigate to http://localhost:8080/path/to/file I开发者_如何学运维 receive this error:

Object #<ServerResponse> has no method 'sendHeader'
(at line 16).

I'm using node-v0.4.12


In node v0.4.12 there is no method sendHeader but it looks like the method response.writeHead(statusCode, [reasonPhrase], [headers]) has the same API, so you could just try to replace your sendHeader by writeHead.

See : http://nodejs.org/docs/v0.4.12/api/http.html#http.ServerResponse


Anyone reading this recently, should also note that the response object uses response.end() now and not response.close()

0

精彩评论

暂无评论...
验证码 换一张
取 消