我需要借助node.js获取文件的文件类型来设置内容类型。我知道我可以轻松检查文件扩展名,但我也有没有扩展名的文件,其内容类型应为 image/png
, text/html
aso。
这是我的代码(我知道它没有多大意义,但这是我需要的基础):
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 中没有找到对应的函数所以如果有人能告诉我怎么做,我会很高兴。
最佳答案
有一个帮助库用于查找 mime 类型 https://github.com/broofa/node-mime
var mime = require('mime');
mime.getType('/path/to/file.txt'); // => 'text/plain'
但它仍然使用扩展名进行查找
关于javascript - Node.js - 文件系统获取文件类型,2012 年左右的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10431845/