小编典典

Node.js-文件系统获取文件类型,2012年左右解决方案

node.js

我需要在node.js的帮助下获取文件的文件类型以设置内容类型。我知道我可以很容易地检查文件的扩展名,但我也得到了一个没有扩展名的文件应有的内容类型image/pngtext/html麻生太郎。

这是我的代码(我知道这没有多大意义,但这是我需要的基础):

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中找到该函数,因此如果有人可以告诉我该怎么做,我会很高兴。


阅读 284

收藏
2020-07-07

共1个答案

小编典典

看一下mmmagic模块。它是一个libmagic绑定,似乎可以完全满足您的要求。

2020-07-07