我用下面的脚本,以显示我的浏览器的HTML文件:Node.js的发送静态文件,如HTML文件
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/");
但是,当我尝试导航到http://localhost:8080/path/to/file
我收到此错误:
Object #<ServerResponse> has no method 'sendHeader'
(at line 16).
我使用节点v0.4.12
thansk!还有其他的结构,我不得不重写(例如close()widht end()),但现在它工作 –