Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement virtual directories with node.js and express?

I want to use the express static server configuration for implementing an static server:

app.configure(function() {
    app.use(express.static(__dirname + '/public'));
});

But I want to map the URL http://myhost/url1 to directory C:\dirA\dirB and http://myhost/url2 to directory C:\dirC

How can it be implemented using express.static?

like image 435
gztomas Avatar asked May 16 '12 12:05

gztomas


People also ask

Is Express needed for node JS?

It is not necessary to use Express. Express is just a library that uses Node-Functions to make it easier for you to implement a Webserver.

What is Express () in node JS?

Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.

How do I create a directory in node JS?

mkdir() method i Node. js is used to create a directory asynchronously. Parameters: This method accept three parameters as mentioned above and described below: path: This parameter holds the path of the directory has to be created.


2 Answers

This should work for you:

var serveStatic = require( "serve-static" );
app.use('/url1', serveStatic('c:\\dirA\\dirB'));
app.use('/url2', serveStatic('C:\\dirC'));

Take a look at the documentation for app.use().

like image 75
MiniGod Avatar answered Oct 24 '22 04:10

MiniGod


Depending on how many directories you're planning to map this way, you could simply make symlinks for those directories in your public folder.

In Windows:

mklink /D c:\dirA\dirB public\url1

In Linux or OSX:

ln -s /dirA/dirB public/url1

Then your static assets server should serve from those directories transparently (I've never tested on Windows but I don't see why it wouldn't work).

Alternatively, if you wanted to include some kind of dynamic routing, you could write your own middleware to replace express.static which is actually connect.static under the hood. Take a look at static.js in the connect source and see how it's implemented, it should be fairly straightforward to write your own variation.

like image 40
Daniel Mendel Avatar answered Oct 24 '22 04:10

Daniel Mendel