Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressJs - where express.static(__dirname) point to?

var express = require('express');
var app = express();
port = process.argv[2] || 8000;

app.configure(function () {
    app.use(
        "/", 
        express.static(__dirname) 
    );
});
app.listen(port);

I removed this piece of line below and i got an error while loading localhost

app.configure(function () {
        app.use(
            "/", 
            express.static(__dirname) 
        );
    });
  1. What does the app.use method do?.
  2. What does the express.static method do? and where does the __dirname points to?.
like image 693
Kevin Avatar asked Sep 19 '13 22:09

Kevin


2 Answers

What does the app.use method do?.

Express has a Middleware which can be configured using app.configure where we can invoke use app.use(). Middleware is used by routes, lets take i called app.use(express.bodyParser()) which added this layer to my Middleware stack. This ensures that for all incoming requests the server parses the body which Middleware takes cares of. This happens because we added the layer to our Middleware .

http://www.senchalabs.org/connect/proto.html#app.use

What does the express.static method? and where does the __dirname points to?.

The code creates an Express server, adds the static Middleware and finally starts listening on port 3000 or provided port.

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

The above code is equivalent to below, which you make you understand.

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

The static middleware handles serving up the content from a directory. In this case the 'root' directory is served up and any content (HTML, CSS, JavaScript) will be available. This means if the root directory looks like:

index.html
js - folder
css - folder

For more references on the same topic, below are stackoverflow links associated.

  • Express app.use
  • What does middleware and app.use actually mean in Expressjs?
like image 115
Thalaivar Avatar answered Oct 02 '22 15:10

Thalaivar


In Node, the __dirname is a global object that contains the name of the directory that the executing script resides from. For example, if you are running node script.js from /home/user/env, then __dirname will contain `/home/user/env.

The method app.use() is a function inherited from the Connect framework, which is the framework Express is written on. The method attaches a middleware function to the application stack, which runs every time Express receives a request.

The code you showed mounts a static server to the path / that reads from the directory the script is executing from:

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

If you were to change the path to /path, then the static file server will serve static files from that path instead. If you specify no path, then / is used by default.

As for what express.static() does itself, it accepts a path and returns a middleware function that listens on requests. This is how the middleware works:

  1. Check if the request method is GET or HEAD. If neither, ignore the request.
  2. Parse the path and pause the request.
  3. Check if there is a default redirect. If so, redirect with a HTTP 303.
  4. Define the handlers for if a directory or error is encountered.
  5. Pass everything to the send module for MIME identification and file serving.

Here is the static() middleware source from Connect for reference:

exports = module.exports = function(root, options) {
  options = options || {};

  // root required
  if (!root) throw new Error('static() root path required');

  // default redirect
  var redirect = false !== options.redirect;

  return function staticMiddleware(req, res, next) {
    if ('GET' != req.method && 'HEAD' != req.method) return next();
    var path = parse(req).pathname;
    var pause = utils.pause(req);

    function resume() {
      next();
      pause.resume();
    }

    function directory() {
      if (!redirect) return resume();
      var pathname = url.parse(req.originalUrl).pathname;
      res.statusCode = 303;
      res.setHeader('Location', pathname + '/');
      res.end('Redirecting to ' + utils.escape(pathname) + '/');
    }

    function error(err) {
      if (404 == err.status) return resume();
      next(err);
    }

    send(req, path)
      .maxage(options.maxAge || 0)
      .root(root)
      .index(options.index || 'index.html')
      .hidden(options.hidden)
      .on('error', error)
      .on('directory', directory)
      .pipe(res);
  };
};
like image 39
hexacyanide Avatar answered Oct 02 '22 14:10

hexacyanide