我用下面的腳本,以顯示我的瀏覽器的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()),但現在它工作 –