1

This works

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

// initialize session, redis server will be used if it's running otherwise will store in memory
require('./config/session.js')(app, function () {
    // configurations
    require('./config/bodyparser.js')(app);
    require('./config/cookieparser.js')(app);
    require('./config/compression.js')(app);
    //require('./config/other.js')(app, express);
    app.use(express.static('./public', { /*maxAge: 86400000*/}));

    app.listen(3000, function () { console.log('running...'); });
});

But if I uncomment require other.js and comment app.use it doesn't. Here is the other.js file.

module.exports = function (app, express)
{
    app.use(express.static('../public', { /*maxAge: 86400000*/}));

    return app;
}

Tried different relatives paths but all failed. Here is the project structure

-config
--other.js
-public
-app.js

The error I get is

Cannot GET /index.html

on my browser, no error in console.

4
  • Any error message? What do you mean exactly by "it doesn't work", please? Commented Jan 18, 2016 at 15:52
  • you right I will edit my question Commented Jan 18, 2016 at 15:54
  • If you update other.js to use ./public as the static folder does it work? Commented Jan 18, 2016 at 15:58
  • @SlashmanX yes it works, I tried all things like ./../public, .././public but didn't try leave it as it is :) give an answer below and I will accept it. Actually it makes sense now. Commented Jan 18, 2016 at 16:01

1 Answer 1

2

The issue here is that when you require the other.js file, the relative path is using the cwd of app.js. The best way to avoid this (and avoid the hassle with relative paths) is to use path.resolve and the __dirname variable.

__dirname is a special Node.js variable that always equals the current working directory of the file it's in. So combined with path.resolve you can always be sure that no matter where the file is being require'd it uses the correct path.

In other.js:

var path = require('path');
....
app.use(express.static(path.resolve(__dirname, '../public')));

Or you could simply update other.js to use ./public but I believe the above is better practice as if you move the app.js or require other.js in a different folder it won't resolve correctly

Info on path.resolve here

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

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.