patrick hollweck patrick hollweck - 9 months ago 39
Javascript Question

Express.js Route orgainisation

When I set-up some Routes i normaly do it like this:

app.get('/x', function(req, res) {
res.sendFile(path.join(__dirname + '/public/.../index.html'));});

The Problem with this is if you have JS or CSS in the Route Folders you cant host them.

So often I just added

app.get('/public/.../js/index.js', function(req, res) {res.sendFile (__dirname + '/public/.../js/index.js');});
app.get('/public/.../css/style.css', function(req, res) {res.sendFile (__dirname + '/public/.../css/style.css');});

just below the Route to make the JS and CSS accessible.

I already host library with express static

app.use('/lib', express.static('lib'));

But that is not Possible for JS and CSS in the Route folders (/public/.../js)

  • Is There a better Way to organize my files that are in the route folders ?

Answer Source

You might use virtual path, keeping your current directory structure, adding following route you can refer all your static files with /static prefix from under ./public subdirectory:

app.use('/static', express.static('public'))

E.g. you would be able to refer http://your_server/static/public/.../js/index.js. Please be aware, that in such case all files under /public might be accessed via /static prefix, so you should not have server code or server configs there.

Ideally for clarity you should host and refer all your static files from one root folder with type subfolders (e.g. /static/js, /static/css):

app.use('/static', express.static('static'))