javascriptnode.jsnode-static

node-static cannot serve a folder above current folder


I don't know if this is a limitation to node-static or is it a bug in my code, but I can't seem to get it to serve files above or beyond the current directory. My current directory structure is this:

project
    public
        ...public stuff here...
    system
        core
           server.js

server.js lives in core directory, making the path to public as ../../public - but this code won't run. It returns a 404.

staticServer = new (static.Server)('../../public');

webServer = http.createServer(function (request, response) {
    staticServer.serve(request,response);
})

webServer.listen(appServerConfig.port, appServerConfig.address);

However, if I change the structure to make the public folder live beside server.js and change the code accordingly, it works:

project
    system
        core
           server.js
           public
               ...public stuff here...


staticServer = new (static.Server)('./public');

webServer = http.createServer(function (request, response) {
    staticServer.serve(request,response);
})

webServer.listen(appServerConfig.port, appServerConfig.address);

Why is this so?


Solution

  • Be aware that using relative paths will resolve those paths relative to the current working directory of the node.js process, that is, the directory you were in when you ran node server.js. So as coded, your could looks OK to me as long as you are in the core directory when you launch node. Are you sure you always launch node from the core directory?

    If you want to be independent of the cwd (more robust IMHO), use __dirname to get the absolute directory path of the current file and then tack on your relative paths to that: __dirname + '/../../public'.

    Beyond that, consider fs.realpath to resolve those. I can't say whether node-static in particular has special code to prevent this, but most other modules I've seen such as connect's static middleware will happily serve any arbitrary directory without special restrictions.