Node.js - 文件系统获取文件类型,解决方案大约在2012年 [英] Node.js - File System get file type, solution around year 2012

查看:85
本文介绍了Node.js - 文件系统获取文件类型,解决方案大约在2012年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在node.js的帮助下获取文件的文件类型来设置内容类型。我知道我可以轻松检查文件扩展名,但我也有没有扩展名的文件应该有内容类型 image / png text / html aso。

I need to get the file type of a file with the help of node.js to set the content type. I know I can easily check the file extension but I've also got files without extension which should have the content type image/png, text/html aso.

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

This is my code (I know it doesn't make much sense but that's the base I need):

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 所以如果有人能告诉我怎么做,我会很高兴。

I haven't found a function for that in the API so I would be happy if anyone can tell me how to do it.

推荐答案

查看 mmmagic模块。它是一种libmagic绑定,似乎完全符合你的要求。

Have a look at the mmmagic module. It is a libmagic binding and seems to do exactly what you want.

这篇关于Node.js - 文件系统获取文件类型,解决方案大约在2012年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆