Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  159] [ 1]  / answers: 1 / hits: 30442  / 11 Years ago, thu, september 19, 2013, 12:00:00
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?.


More From » node.js

 Answers
100

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.




[#75582] Wednesday, September 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tonisandyp

Total Points: 694
Total Questions: 97
Total Answers: 77

Location: British Indian Ocean Territory
Member since Tue, Feb 22, 2022
2 Years ago
;