You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit b2db2c2
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: chapters/modules.md
+12-3Lines changed: 12 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -10,7 +10,7 @@ Lets create a utility module named _utilities_, which will contain a `merge()` f
10
10
var utilities = {};
11
11
utilities.merge = function(obj, other) {};
12
12
13
-
CommonJS modules remove this conflict by "wrapping" the contents of a JavaScript file with a closure similar to what is shown below, however more pseudo globals are available to the module, not just `exports` and `module`. The `exports` object is then returned when a user invokes `require('utils')`.
13
+
CommonJS modules remove this conflict by "wrapping" the contents of a JavaScript file with a closure similar to what is shown below, however more pseudo globals are available to the module, not just `exports`, `require`, and `module`. The `exports` object is then returned when a user invokes `require('utils')`.
14
14
15
15
var module = { exports: {}};
16
16
(function(module, exports){
@@ -53,7 +53,6 @@ Node also supports the idea of _index_ JavaScript files, to illustrate this exam
53
53
54
54
The contents of _./math/add.js_ show us a new technique, here we use `module.exports` instead of `exports`. Previously mentioned was the fact that `exports` is not the only object exposed to the module file when evaluated, we also have access to `__dirname`, `__filename`, and `module` which represents the current module. Here we simply define the module export object to a new object, which happens to be a function.
55
55
56
-
57
56
module.exports = function add(a, b){
58
57
return a + b;
59
58
};
@@ -72,4 +71,14 @@ if we change our module slightly, we can remove `.Animal`:
72
71
73
72
which can now be used without the property:
74
73
75
-
var Animal = require('./animal');
74
+
var Animal = require('./animal');
75
+
76
+
## Asynchronous Require
77
+
78
+
Node provides us with an asynchronous version of `require()`, aptly named `require.async()`. Below is the sample example previously shown for our _utilities_ module, however non blocking. `require.async()` accepts a callback of which the first parameter `err` is `null` or an instanceof `Error`, and then the module exports. Passing the error (if there is one) as the first argument is an extremely common idiom in node for async routines.
0 commit comments