Node.js – 文件系统获取文件types

我需要借助node.js来获取文件的文件types来设置内容types。 我知道我可以很容易地检查文件扩展名,但我也有没有扩展名的文件应该有内容types的image/pngtext/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); 

我还没有find在API中的function,所以我会很高兴,如果任何人都可以告诉我如何做到这一点。

看看mmmagic模块 。 这是一个libmagic绑定,似乎正是你想要的。

有一个助手库查找MIMEtypeshttps://github.com/broofa/node-mime

 var mime = require('mime'); mime.lookup('/path/to/file.txt'); // => 'text/plain' 

但它仍然使用扩展名查找

你应该看看命令行工具file (Linux)。 它试图根据文件的前几个字节猜测文件types。 您可以使用child_process.spawn从节点内运行它。

你想要查找MIMEtypes,幸好节点有一个方便的库,只是为了:

https://github.com/bentomas/node-mime#readme

编辑:

你应该看看一个静态的资产服务器,而不是自己设置这些东西。 你可以使用express来做到这一点,或者有很多静态文件模块,例如欣喜若狂 。 另一方面,你应该使用nginx来提供静态文件。