How do I set a MIME type before sending a file in Node.js?
Search google for the Content-Type HTTP header.
Then figure out how to set it with http://expressjs.com/api.html#res.set
Oops, the example includes your answer ;)
Simply check the file ending, if it's .js
, set the appropriate MIME type to make browsers happy.
EDIT: In case this is pure node, without express, look here: http://nodejs.org/api/http.html#http_response_setheader_name_value
I figured it out!
Thanks to @rdrey's link and this node module I managed to correctly set the MIME type of the response, like this:
function handler(req, res) {
var url = convertURL(req.url);
if (okURL(url)) {
fs.readFile(url, function(err, data) {
if (err) {
res.writeHead(404);
return res.end("File not found.");
}
res.setHeader("Content-Type", mime.lookup(url)); //Solution!
res.writeHead(200);
res.end(data);
});
} else {
res.writeHead(403);
return res.end("Forbidden.");
}
}