Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  118] [ 7]  / answers: 1 / hits: 72500  / 12 Years ago, thu, may 3, 2012, 12:00:00

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.


More From » node.js

 Answers
47

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


[#85822] Wednesday, May 2, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raynamadilynl

Total Points: 653
Total Questions: 110
Total Answers: 98

Location: Honduras
Member since Sat, Jul 24, 2021
3 Years ago
;