node.jsnode.js-connect

Node Connect Static set Content-type text/plain not working


I am trying to set the content type of the files served by connect.static to text/plain. I thought this would work, but connect seems to still be detecting the content type fomr the extension with the mime module.

var connect = require("connect")

connect()
    .use(connect.static(__dirname + "/public"))
    .use(function(req, res, next) {
        res.setHeader("Content-Type", "text/plain");
    })
    .listen(process.env.PORT);

Is there any easy way of doing this? Maybe screwing around in connects instance of mime before it can get to it? Or will I have to rewrite connects static middleware?


Solution

  • If you have control of the filenames within the public directory, the easiest approach is to ensure that they end in '.txt', so that the mime map provides the send function with the correct Content-Type.

    Failing that, you could change the default mime type:

    var connect = require("connect")
    
    var mime = connect.static.mime;
    mime.default_type = mime.lookup('text');
    
    connect()
        .use(connect.static(__dirname + "/public"))
        .listen(process.env.PORT);
    

    Alternatively, if you really want every file served as text/plain, just set the Content-Type header before the static middleware is invoked. It only adds the header if it isn't already present on the response:

    var connect = require("connect")
    
    connect()
        .use(function(req, res, next) {
            res.setHeader("Content-Type", "text/plain");
            next();
        })
        .use(connect.static(__dirname + "/public"))
        .listen(process.env.PORT);