Configuring two different static directories in the node.js Express framework

Is it possible? I would like to set up two different directories for serving static files. Let say / public and / mnt

+68
static express
May 12 '11 at 4:53
source share
3 answers

You can also specify a way for static files to be transferred to the Internet by specifying an additional parameter (first) to use() as follows:

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

This way you get two different directories on the Internet that reflect your local directories, and not just one URL path that fails between two local directories.

In other words, the URL pattern is:

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

Serves to download files from the local public directory, and:

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

Serves to download files from the local directory public2 .

By the way, this is also useful if you do not want static to serve files from the root of your server, but rather from a more qualified path.

NTN

+110
Sep 28 '12 at 22:51
source share

This is not possible for a single intermediate injection, but you can add static middleware several times:

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

Explanation

See connect / lib / middleware / static.js # 143 :

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

There is options.root - the static root that you define in the call to express.static or connect.static , and path is the request path.

See 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); 

The path is checked only once, and if the file is not found, the request proceeds to the next middleware.

Update for connect 2.x

Code links are not relevant for Connect 2.x, but using static middleware is still possible, as before.

+37
May 12 '11 at 10:23
source share

You can also "merge" directories into one visible directory

Directory structure

  • / static
  • / alternate_static

the 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. However, watch out for file clovers.

+32
Feb 12 '13 at 19:34
source share



All Articles