我需要借助node.js来获取文件的文件类型以设置内容类型。我知道我可以很容易地检查文件扩展名,但我也有没有扩展名的文件,其内容类型应该是image/png,text/html aso。Node.js - 文件系统获取文件类型
这是我的代码(我知道这并没有太大的意义,但是这就是我需要的基础):
var http = require("http"),
fs = require("fs");
http.createServer(function(req, res) {
var data = "";
try {
/*
* Do not use this code!
* It's not async and it has a security issue.
* The code style is also bad.
*/
data = fs.readFileSync("/home/path/to/folder" + req.url);
var type = "???"; // how to get the file type??
res.writeHead(200, {"Content-Type": type});
} catch(e) {
data = "404 Not Found";
res.writeHead(404, {"Content-Type": "text/plain"});
}
res.write(data);
res.end();
}).listen(7000);
我还没有找到一个函数,该函数在API,所以我会很高兴如果有人能告诉我该怎么做。
2012-05-03
noob
+6
'readFileSync' on每个请求?听起来不是一个好主意...... –
+3
@ThiefMaster正如他所说,这只是虚拟代码(至少这就是我认为的“我知道这并没有多大的意义,但这是我需要的基础”意思是)。 –