Node.js - 文件系统获取文件类型 [英] Node.js - File System get file type

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

问题描述

我需要借助node.js获取文件的文件类型来设置内容类型。我知道我可以很容易地检查文件的扩展名,但是我也得到了没有扩展名的文件,这些文件的内容类型应该是 image / png text / html aso。



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


$ b $ pre $ var http = require(http),
fs = require(fs);
http.createServer(function(req,res){
var data =;
try {
/ *
*不要使用这段代码!
*这不是异步的,它有一个安全问题
*代码风格也是不好的
* /
data = fs.readFileSync(/ home / path / to / folder + req.url);
var 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 ,所以如果有人能告诉我怎么做,我会很高兴的。

解决方案

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


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);

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.

解决方案

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

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

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