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


Question

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

1
18
8/20/2011 11:09:55 AM

Accepted Answer

Connect will automatically set the content type, unless you explicitly set it yourself. Here's the snippet that does it. It uses mime.lookup and mime.charsets.lookup

// mime type
type = mime.lookup(path);

//<SNIP>....

// header fields
if (!res.getHeader('content-type')) {
  var charset = mime.charsets.lookup(type);
  res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
}

If this isn't working for you, post your code as your custom code is likely interfering with the default behavior somehow.

8
7/14/2012 4:34:38 PM

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon