Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: require('events').EventEmitter;

Why

var EventEmitter = require('events').EventEmitter;
var channel = new EventEmitter();

works, but

var EventEmitter = require('events');
var channel = new EventEmitter();

does not work! Actually, I have another totally different example,

var Currency = require('./currency)
var Cu = new Currency();

works, but

var Currency = require('./currency).Currency;
var Cu = new Currency();

does not work. Here is my currency.js:

function Currency(canadianDollar) {
    this.canadianDollar = canadianDollar;
}

module.exports = Currency;

Currency.prototype.cal = function(amount) {
    return amount * this.canadianDollar;
}
like image 527
Benson Avatar asked Sep 12 '25 16:09

Benson


2 Answers

Because this is the way the API is written. A simplified example of "events" module would look like:

module.exports = {
    EventEmitter: function () {
        // ...
    }
};

In the above case require('events'); would return an Object containing EventEmitter, but require('events').EventEmitter would return the actual EventEmitter function you are likely interested in instantiating.

Thought it would be good to mention that the API designer could indeed export the EventEmitter function directly with module.exports = function () { ... }; however, they decided to leave space for other potentially useful properties of the "events" module.

Edit

Regarding module.exports = EventEmitter; in https://github.com/joyent/node/blob/master/lib/events.js, on the following lines you can find:

// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;

I suppose that starting from version 0.11 you can run var Emitter = require('events');, but in 0.10.x you are stuck with require('events').EventEmitter.

like image 93
Oleg Avatar answered Sep 14 '25 04:09

Oleg


require returns exactly what you put in module.exports object. So if you have module.exports = Currency; then require returns Currency and if you have exports.Currency = Currency require will return { Currency : Currency } object.

if you want this to work both ways, just do Currency.Currency = Currency; module.exports = Currency. in latest node releases they do like this with EventEmitter

like image 32
vkurchatkin Avatar answered Sep 14 '25 04:09

vkurchatkin