您的位置:首页 > Web前端 > Node.js

node.js 读取文件

2012-02-07 15:37 330 查看

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;
console.log(uri);
var filename = path.join(process.cwd(), uri);
console.log(filename);
path.exists(filename, function(exists) {
if(!exists) {
response.writeHeader(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}

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

response.writeHeader(200);
response.write(file, "binary");
response.end();
});
});
}).listen(8081);

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

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: