Doug Beney Doug Beney - 1 month ago 10x
Javascript Question

Running node app from a different directory makes static folder act funny

Here's the gist of my project structure:

  • /

    • node_modules/

    • public/

      • css/

        • main.css

    • server/

      • views/

      • app.js

    • package.json

Here's my super simple app.js:

var express = require('express');
var app = express();

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

app.listen(3000, function(){
console.log('live at http://localhost:3000');

Now, when I am in the root directory, run
and load up the url
everything loads perfectly as expected.

However, when I am in the server/ directory, run
node app.js
, and load up the same url, I get the error
Cannot GET /public/css/main.css

Is there a way for me to fix this so I can run my project from any directory?


Replace this:

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

with this:

var path = require('path');

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

The problem with the first snippet is that 'public' is interpreted as relative to the current working directory. With the second snippet, it's relative to the location of app.js - which isn't dependent upon your current working directory.