Node.js - File System get file type, solution arou

2019-02-01 20:35发布

问题:

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.

回答1:

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



回答2:

There is a helper library for looking up mime types https://github.com/broofa/node-mime

var mime = require('mime');

mime.lookup('/path/to/file.txt');         // => 'text/plain'

But it still uses the extension for lookup though



回答3:

You should have a look at the command line tool file (Linux). It attempts to guess the filetype based on the first couple of bytes of the file. You can use child_process.spawn to run it from within node.



回答4:

You want to be looking up the mime type, and thankfully node has a handy library just for that:

https://github.com/bentomas/node-mime#readme

edit:

You should probably look into a static asset server and not be setting any of this stuff yourself. You can use express to do this really easily, or there's a whole host of static file modules, e.g. ecstatic. On the other hand you should probably use nginx to serve static files anyway.



回答5:

I used this:

npm install mime-types

And, inside the code:

var mime = require('mime-types');
tmpImg.contentType = mime.lookup(fileImageTmp);

Where fileImageTmp is the copy of image stored on the file system (in this case tmp).

The result I can see is: image/jpeg



回答6:

2018 solution

The accepted answer appears to have a Python dependency and the other answers are either out-of-date or presume the file name has some sort of extension.

Please find my more up-to-date answer here