Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express js static relative parent directory

I'm currently experiencing some minor problems with serving static files through expressJs.

My directory structure is as following:

  • public
    • css
    • lib
  • src
    • views
    • home
      • index.html
    • server.js

In my index.html file i have prefixed all my assets with a leading slash.

My static setup is as following: app.use(express.static(path.resolve(__dirname + '../' + 'public')));

But for some reason my static files are not getting served.

I was thinking that this is a crossdomain call or something... I'm currently using cloud9 IDE, might this have to do with it somehow?

like image 284
KyorCode Avatar asked Dec 02 '13 06:12

KyorCode


People also ask

How to serve static files express js?

To serve static files such as images, CSS files, and JavaScript files, use the express. static built-in middleware function in Express. The root argument specifies the root directory from which to serve static assets.

What is express static for?

express. static exposes a directory or a file to a particular URL so it's contents can be publicly accessed.

How to serve static files?

To serve static files for Go 1.12+ in the standard environment, you define the handlers in your app. yaml file using either the static_dir or static_files elements. The content in the static files or static directories are unaffected by the scaling settings in your app.


2 Answers

__dirname doesn't have a trailing slash, so __dirname + '../' results in DIRNAME../ (which isn't valid).

Instead, use:

__dirname + '/../public'              ^ extra slash 
like image 33
robertklep Avatar answered Oct 13 '22 22:10

robertklep


You should use path.join instead of manually concatening path components. It uses path.normalize, which resolves . and .., handles multiple or trailing slashes, and uses the appropriate file separator for your platform (see: path.sep).

For example,

var path = require('path');  var express = require('express');  var app = express();  app.use(express.static(path.join(__dirname, '../public'))); 
like image 178
thomasd Avatar answered Oct 13 '22 22:10

thomasd