Reputation: 3686
I'm new to node and JS and was working thorough the socket.io chat example (http://socket.io/get-started/chat/). I came across this code in the server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
I've looked at other tutorials and never seen double parentheses after require before. What does the (http)
part do? Is it a parameter for require, doest it change the type, or something else?
Thanks!
Upvotes: 10
Views: 955
Reputation: 384
To expand if you had a library http
and it has a exported module server
.
Lets say we picked apart the line:
var http = require('http').Server(app);
into two lines:
var http = require('http')
Imports the "http" module library as a JSON object into the http variable. This module library has a bunch of modules that you can access now by calling them via the http var.
httpServer = http.Server(app)
This loads the Server module with the express data that you called above (Kind of line a constructor) and puts it into the httpServer var.
The difference above is that instead of the two steps, they are condensing it into one, so that http has the Server module inside it instead of the entire http library. This can be useful if you only want to use that specific part of the http library.
Upvotes: 2
Reputation: 23277
In JavaScript, function is the First-class citizen. This means that it can be returned by another function.
Consider the following simple example to understand this:
var sum = function(a) {
return function(b) {
return a + b;
}
}
sum(3)(2); //5
//...or...
var func = sum(3);
func(2); //5
In your example, require('socket.io')
returns another function, which is called immediately with http
object as a parameter.
Upvotes: 12
Reputation: 462
Nodejs allows you to assign an object/function to the exported module using the statement module.exports = something
. So each one of those statements are importing a library, and then running the function that was assigned to what was exported.
For example, here is the source code for express where they export the createApplication
function.
And here's an article where they go into a bit more detail.
Upvotes: 0