Add documentation around module.exports and scope of global objects
authorRyan Dahl <ry@tinyclouds.org>
Mon, 11 Apr 2011 23:48:18 +0000 (16:48 -0700)
committerRyan Dahl <ry@tinyclouds.org>
Tue, 12 Apr 2011 00:01:25 +0000 (17:01 -0700)
Closes GH-852.

doc/api/globals.markdown
doc/api/modules.markdown

index 3a561a3..fb971cb 100644 (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.
index 68c36c0..07ff31f 100644 (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