相关疑难解决方法(0)

Node.js - 文件系统获取文件类型,解决方案大约在2012年

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

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

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(); …
Run Code Online (Sandbox Code Playgroud)

javascript filesystems file-type node.js

24
推荐指数
4
解决办法
5万
查看次数

标签 统计

file-type ×1

filesystems ×1

javascript ×1

node.js ×1