Setting up two different static directories in node.js Express framework

后端 未结 6 702
北恋
北恋 2020-11-30 22:21

Is it possible? I would like to set up two different directories to serve static files. Let\'s say /public and /mnt

6条回答
  •  情深已故
    2020-11-30 22:35

    It's not possible by one middleware injection, but you can inject static middleware multiple times:

    app.configure('development', function(){
        app.use(express.static(__dirname + '/public1'));
        app.use(express.static(__dirname + '/public2'));
    });
    

    Explanation

    Look at connect/lib/middleware/static.js#143:

    path = normalize(join(root, path));
    

    There is options.root is static root, which you define in express.static or connect.static call, and path is request path.

    Look more at connect/lib/middleware/static.js#154:

      fs.stat(path, function(err, stat){
        // ignore ENOENT
        if (err) {
          if (fn) return fn(err);
         return ('ENOENT' == err.code || 'ENAMETOOLONG' == err.code)
           ? next()
           : next(err);
    

    Path checked only once, and if file not found request passed to next middleware.

    Update for Connect 2.x

    Links to code are inactual for Connect 2.x, but multiple static middleware usage are still posible as before.

提交回复
热议问题