Add documentation around module.exports and scope of global objects

Closes GH-852.
This commit is contained in:
Ryan Dahl 2011-04-11 16:48:18 -07:00
parent 6b5a7033bb
commit d2298d225c
2 changed files with 55 additions and 1 deletions

View File

@ -1,6 +1,7 @@
## Global Objects
These object are available in the global scope and can be accessed from anywhere.
These object are available in all modules. Some of these objects aren't
actually in the global scope but in the module scope - this will be noted.
### global
@ -18,6 +19,8 @@ The process object. See the [process object](process.html#process) section.
### require()
To require modules. See the [Modules](modules.html#modules) section.
`require` isn't actually a global but rather local to each module.
### require.resolve()
@ -44,6 +47,8 @@ Example: running `node example.js` from `/Users/mjr`
console.log(__filename);
// /Users/mjr/example.js
`__filename` isn't actually a global but rather local to each module.
### __dirname
The dirname of the script being executed.
@ -53,6 +58,8 @@ Example: running `node example.js` from `/Users/mjr`
console.log(__dirname);
// /Users/mjr
`__dirname` isn't actually a global but rather local to each module.
### module
@ -66,3 +73,5 @@ for more information.
### clearInterval(t)
The timer functions are global variables. See the [timers](timers.html) section.
`module` isn't actually a global but rather local to each module.

View File

@ -139,6 +139,51 @@ Modules are cached after the first time they are loaded. This means
(among other things) that every call to `require('foo')` will get
exactly the same object returned, if it would resolve to the same file.
### module.exports
The `exports` object is created by the Module system. Sometimes this is not
acceptable, many want their module to be an instance of some class. To do this
assign the desired export object to `module.exports`. For example suppose we
were making a module called `a.js`
var EventEmitter = require('events').EventEmitter;
module.exports = new EventEmitter();
// Do some work, and after some time emit
// the 'ready' event from the module itself.
setTimeout(function() {
module.exports.emit('ready');
}, 1000);
Then in another file we could do
var a = require('./a');
a.on('ready', function() {
console.log('module a is ready');
});
Note that assignment to `module.exports` must be done immediately. It cannot be
done in any callbacks. This does not work:
x.js:
setTimeout(function() {
module.exports = { a: "hello" };
}, 0);
y.js
var x = require('./x');
console.log(x.a);
### All Together...
To get the exact filename that will be loaded when `require()` is called, use