Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express: Setting content-type based on path/file?

I know Express has the res.contentType() method, but how to set automatically content type based on path/file (including static content)?

like image 647
mahemoff Avatar asked Aug 18 '11 15:08

mahemoff


2 Answers

Also, if you want to extend the mime-types that express(connect) knows about, you can do

express.static.mime.define({'text/plain': ['md']}); 

or

connect.static.mime.define({'text/plain': ['md']}); 

PS: the mime module is now located at https://github.com/broofa/node-mime

like image 50
Andrei Neculau Avatar answered Sep 25 '22 12:09

Andrei Neculau


The Express documentation shows that it can do this if you pass in the file name.

var filePath = 'path/to/image.png'; res.contentType(path.basename(filePath)); // Content-Type is now "image/png" 

[Edit]

Here's an example which serves files from a relative directory called static and automatically sets the content type based on the file served:

var express = require('express'); var fs      = require('fs');  var app = express.createServer();  app.get('/files/:file', function(req, res) {   // Note: should use a stream here, instead of fs.readFile   fs.readFile('./static/' + req.params.file, function(err, data) {     if(err) {       res.send("Oops! Couldn't find that file.");     } else {       // set the content type based on the file       res.contentType(req.params.file);       res.send(data);     }        res.end();   });  });  app.listen(3000); 
like image 44
Michelle Tilley Avatar answered Sep 24 '22 12:09

Michelle Tilley