I am fairly new to nodejs and have been looking at some code and trying to make sense of it. Can someone please bear with me and help me understand the following code fragments. My questions may be very basic but please understand that I am learning nodejs and express and have been trying hard to understand some existing code. I have marked the code lines with numbers and the questions are posed by the same number.
var ChatApp = global.ChatApp = {}
, conf = ChatApp.conf = require('./conf').config (1)
, http = require('http') (2)
, path = require('path') (3)
, express = require('express')
, app = express()
;
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev')); (6)
app.use(express.bodyParser()); (7)
app.use(express.methodOverride()); (8)
app.use(express.cookieParser('your secret here')); (9)
app.use(express.session({secret: 'PTKACSxSq24PlZ9IAPRMy3_2'})); (10)
app.all('*', function(req, res, next) {
var oneof = false;
if(req.headers.origin) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
oneof = true;
}
if(req.headers['access-control-request-method']) {
res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
oneof = true;
}
if(req.headers['access-control-request-headers']) {
res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
oneof = true;
}
if(oneof) {
res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
} (11)
// intercept OPTIONS method
if (oneof && req.method == 'OPTIONS') {
res.send(200);
}
else {
next();
}
}); (12)
app.use(app.router); (13)
app.use(express.static(path.join(__dirname, 'public')));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
} (15)
server = http.createServer(app); (16)
require('./lib/chat').init(server); (17)
(1) I understand what require does but conf = ChatApp.conf = require('./conf').config ? Are we making a variable conf and making it equal to ChatApp. conf? Also is the require is pointing to parent directory/conf/config ? I ask this because in my parent directory where this file exists , there is no conf folder. There is just a conf. js file but it gets included in this variable (checked with console.log). How does it happen?
(2),(3) require(http) and require(path). Why is the need to include http and path? What purpose do these 2 solve?
(6)app.use(express.logger('dev')) From express website, it is used to log every request. My question is what is the parameter dev in the function for? Is it a path ?
(7) app.use(express.bodyParser()) : From express website: Request body parsing middleware supporting JSON, urlencoded, and multipart requests. This middleware is simply a wrapper the json(), urlencoded(), and multipart() middleware. But what does it really mean? What does express.bodyparser do?
(8) app.use(express.methodOverride()); No explanation on express website. Not sure what it means and why is it used.
(9) express.cookieparser parses the cookie header field. but what is a header field in a cookie. From what I know, a browser cookie has the following fields. Name, Content, Domain, Path, Send For, Expires.
(10) app.use(express.session({secret: 'PTKACSxSq24PlZ9IAPRMy3_2'})); I couldn't find any method called express.session(). What does it do?
(12) For code fragmant 12, I couldn't understand what are we trying to achieve with it?
(13) app.use(app.router) When I did a console.log of app.router, it gave me this
function router(req, res, next){
self._dispatch(req, res, next);
}
Any idea why are we doing this? It appears to be a generic router function but why is the need to include it?
(15) app.get.env gave me development and it is coming from a file within express/lib/application.js. Why are we doing this test?
(16) This is totally confusing. I have seen this
var server = http.createServer() and var app = express() which means express has a built in http server within it but why would be do http.createserver(express()) or http.createserver(app)?
(17) There is a lib/chat folder in my app root but it has a host of files with an index.js file in it. Does it mean to include the index.js file in that or all the js files in the folder? And why the init server?
Any help from anyone would be greatly apreciated.
The following answers won't tell you what the following things are: HTTP request, REST, sessions. Also note that it's rather unlikely that you will ever get so many questions answered again.
(1) I understand what require does but
conf = ChatApp.conf = require('./conf').config? Are we making a variableconfand making it equal toChatApp.conf?
Yes
Also is the require is pointing to parent directory/conf/config?
No. It's requiring either ./conf.js or ./conf.node, .js is preferred. The module exports a config field, which gets accessed.
(2),(3) require(http) and require(path). Why is the need to include http and path? What purpose do these 2 solve?
http is necessary for the HTTP server, path for path-based functions.
(6)app.use(express.logger('dev')) From express website, it is used to log every request. My question is what is the parameter dev in the function for? Is it a path ?
It's the logger middleware from Connect:
devconcise output colored by response status for development use(7) app.use(express.bodyParser()) : From express website: Request body parsing middleware supporting JSON, urlencoded, and multipart requests. This middleware is simply a wrapper the json(), urlencoded(), and multipart() middleware. But what does it really mean? What does express.bodyparser do?
It enables you to parse the body of HTTP requests. If you don't know what a HTTP request is, you might stop to read the rest of the answer, learn a little bit about HTTP, and get back for the rest.
(8) app.use(express.methodOverride()); No explanation on express website. Not sure what it means and why is it used.
Most web browsers only support the HTTP verbs GET and POST. However, in order to provide a RESTful service (another fancy word), one also needs PUT/PATCH and DELETE. methodOveride enables you to create forms which will be sent by POST, but interpreted according to their _method attribute.
(9) express.cookieparser parses the cookie header field. but what is a header field in a cookie. From what I know, a browser cookie has the following fields. Name, Content, Domain, Path, Send For, Expires.
Well, remember about HTTP request? A cookie gets send in the header of your browser's HTTP request. That's the Cookie: header.
(10) app.use(express.session({secret: 'PTKACSxSq24PlZ9IAPRMy3_2'})); I couldn't find any method called express.session(). What does it do?
It enables you to use sessions.
(12) For code fragmant 12, I couldn't understand what are we trying to achieve with it?
This fragment addresses access control for cross-site requests.
(13) app.use(app.router) When I did a console.log of app.router, it gave me this
function router(req, res, next){ self._dispatch(req, res, next); }Any idea why are we doing this? It appears to be a generic router function but why is the need to include it?
app.router will route the requests. For example app.get('/hello-world')´ will take all requests withGET /hello-world. You need to useapp.router` in order to enable this behaviour.
(15) app.get.env gave me development and it is coming from a file within express/lib/application.js. Why are we doing this test?
Because we want to handle errors with a nice error message.
(16) This is totally confusing. I have seen this var server = http.createServer() and var app = express() which means express has a built in http server within it but why would be do http.createserver(express()) or http.createserver(app)?
Because that's the express 3.x way of doing it, it doesn't come with a fully-fledged http server anymore. This way, you can use your app as callback for many other things.
(17) There is a lib/chat folder in my app root but it has a host of files with an index.js file in it. Does it mean to include the index.js file in that or all the js files in the folder? And why the init server?
It includes the index.js. init(server) will probably do some things to the server. You need to check the according file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With