I am currently starting with node.js, so I am for the first time using Js beyond dom manipulation.
I came across a code piece like below. I cant understand it. What is happening? is it a key value object? Is an anonymous function
being passed to 'new'
?
module.exports = {
'new': function(req, res) {
res.view();
},
/**
* Overrides for the settings in `config/controllers.js`
* (specific to UserController)
*/
_config: {}
};
As others have said, this is ultimately just creating an object called module.exports
then assigning two properties to it. One is another object called _config
and the other is a function called new
that expects two arguments.
That's the plain JavaScript explanation.
In node.js, you're also seeing a few conventions in play, which I'll describe below.
One convention is module.exports
.
This is the object that will be made available when some other code loads this file using require()
. It would work something like this:
var m = require('yourmodule.js');
m.new(req, res);
Another convention is the pair of arguments: req, res
.
These are usually parameters that represent a request (like an http.IncomingMessage
) and a response (like a http.ServerResponse
).
Putting it all together, this module is probably defining a Controller that will receive http requests, and render them as responses. It currently does this for new
, and there are probably routes configured elsewhere that call this method when a user requests something like ' http://server.come/user/new '.
Looks like basic JavaScript.
An object named module has a property named exports that is an object.
This object has a property named new whose value is an anonymous function.
In theory you could invoke the method like this:
module.exports.new(someRequest, someResponse);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.