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

*爱你&永不变心* 提交于 2019-11-27 06:31:17
facetcounter

You can also set the path that static files will be served to the web from by specifying an additional (first) parameter to use() like so:

app.use("/public", express.static(__dirname + "/public"));
app.use("/public2", express.static(__dirname + "/public2"));

That way you get two different directories on the web that mirror your local directories, not one url path that fails over between two local directories.

In other words the URL pattern:

http://your.server.com/public/*

Serves files from the local directory public while:

http://your.server.com/public2/*

Serves files from the local directory public2.

BTW this is also useful if you don't want static to serve the files from the root of your server but rather from a more qualified path.

HTH

Randolpho

You can also "merge" directories into a single visible directory

Directory Structure

  • /static
  • /alternate_static

Code

app.use("/static", express.static(__dirname + "/static"));
app.use("/static", express.static(__dirname + "/alternate_static"));

Both static and alternate_static will be served as if they were in the same directory. Watch out for filename clobbers, though.

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.

const express = require('express');
const path = require('path');
const pagesPath = path.join(__dirname, '/cheatsheet');
const cssPath = path.join(__dirname, '/stylesheet');
const port = process.env.PORT || 3000;

var app = express();

app.use("/cheatsheet" ,express.static(pagesPath));
app.use("/stylesheet",express.static(cssPath)); 

app.get('/',(request,response)=>{
    response.send('Hello CSS!!!');
  });

app.get('/bad',(request,response)=>{
response.send({error: 'Bad Request'});

});
app.listen(port, ()=> {
console.log(`Server is running on Port ${port}` );
console.log(__dirname);

});

// folder structure
/cheatsheet/index.html
/stylesheet/style.css
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!