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

标签 javascript node.js filesystems file-type

我需要借助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/

相关文章:

javascript - 似乎无法使用空依赖数组影响 React 的 useEffect() 中的状态。套接字.io

node.js - 使用 multer-s3 将大视频文件上传到 s3

jquery - 从用户的本地系统获取文件的属性(上次修改日期)

webserver - 在网络服务器上存储文档 - 最佳方法

java - 在 Java 中确定文件创建日期

Javascript 调试器(Chrome 和 Webstorm)总是在不存在的断点处中断

javascript - 获取 2 位 float 未按预期工作

javascript - 用其他语言编写 JavaScript

javascript - 在 JavaScript 中测试稀疏数组元素的存在?

node.js - SequelizeConnectionRefusedError/ECONNREFUSED 上的 Node 应用程序崩溃