noo*_*oob 24 javascript filesystems file-type node.js
我需要在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);
Run Code Online (Sandbox Code Playgroud)
我还没有在API中找到这个功能,所以如果有人能告诉我怎么做,我会很高兴.
250*_*50R 31
有一个帮助库,用于查找mime类型https://github.com/broofa/node-mime
var mime = require('mime');
mime.getType('/path/to/file.txt'); // => 'text/plain'
Run Code Online (Sandbox Code Playgroud)
但它仍然使用扩展名进行查找
你想要查找mime类型,谢天谢地,node只为此提供了一个方便的库:
https://github.com/bentomas/node-mime#readme
编辑:
您应该查看静态资产服务器,而不是自己设置任何这些内容.您可以使用express来轻松地执行此操作,或者有一大堆静态文件模块,例如欣喜若狂.另一方面,你应该使用nginx来提供静态文件.
归档时间: |
|
查看次数: |
49310 次 |
最近记录: |