kazu kazu - 1 year ago 232
Node.js Question

Nodejs with express, static dirname

I'm currently working on a web app, using node.js, express and underscoreJS.

I was trying to understand the difference whether I use this or not :

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

The app seems to be faster with it, but I'm not sure that I fully understand the meaning of this.
The meaning aside, if I want to use it on my computer for tests, it doesn't work when I try to use the app with localhost:xxxx (xxxx being the port), I end up having an enoent error, but it works fine on the server, any idea why ?

Sorry if the question seems dumb, I just was assigned to this project and lots of work has already been done before I arrived.

rsp rsp
Answer Source

This line:

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

is for serving static files in Express.

I recently wrote an example of serving static files on GitHub. The main application code is:

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

var htmlPath = path.join(__dirname, 'html');


var server = app.listen(3000, function () {
    var host = 'localhost';
    var port = server.address().port;
    console.log('listening on http://'+host+':'+port+'/');

The line with app.use(express.static(htmlPath)); doesn't make it faster to serve static files - it makes it possible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download