javascript: require('events').EventEmitter;

eventemitter, javascript, node.js

Solution

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`.

Problem

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; } ```

Original source