0

I'm trying to serve static files from Node.js the only problem I'm having, is if I keep going into sub paths, like so:

localhost:3000/foo/bar/baz/quux

Then I have to step up the same amount of times, like this:

../../../../public/javascripts/whatever.js

As you can see that gets really annoying, is there a way to make Express v3 just know so that I can just do /public/javascripts/whatever.js instead of having to step up? Thanks in advance

This is my current static middleware for Express`

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

2 Answers 2

3

If you reference your static files from the root (i.e. src='/some/path/to/file.js'), the url should not matter.

Example Website using Static Routing

Directory Structure

/public
    /css/style.css
    /js/site.js
/vendor/thoughtbrain/js/awesome-town.js
/views/view.html
/app.js

view.html


<!DOCTYPE html>
<html>
  <head>
    <!-- These files are served statically from the '/public' directory... -->
    <link href="/css/style.css" rel="stylesheet" >
    <script src="/js/site.js"></script>
    <!-- ... while this is "mounted" in virtual '/public' -->
    <script src="/public/js/awesome-town.js"></script>
  </head>
<body><p>Express</p></body>
</html>

app.js

var express = require('express'),
    http = require('http'),
    path = require('path'),
    app = express();

// Remember: The order of the middleware matters!

// Everything in public will be accessible from '/'
app.use(express.static(path.join(__dirname, 'public')));

// Everything in 'vendor/thoughtbrain' will be "mounted" in '/public'
app.use('/public', express.static(path.join(__dirname, 'vendor/thoughtbrain')));

app.use(express.static(path.join(__dirname, 'views')));

app.all('*', function(req, res){
  res.sendfile('views/view.html')
});

http.createServer(app).listen(3000);

With this application running,

http://localhost:3000

and

http://localhost:3000/foo/bar/baz/quux

both serve view.html and all referenced assets resolve.

Express Framework has a section on the use of static middleware here.

Sign up to request clarification or add additional context in comments.

Comments

0

With that static() configuration, Express is already at least capable of finding /public/javascripts/whatever.js.

Though, it does depend on whether your public folder is in the same directory as your script (due to the use of __dirname when specifying the path).

If it is, the URL prefix /public should map to the file-system prefix of ./public (with . being __dirname) so that:

A URL of `/public/javascripts/whatever.js`
Maps to `./public/javascripts/whatever.js`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.