diff options
author | isaacs <i@izs.me> | 2011-09-13 10:59:42 -0700 |
---|---|---|
committer | isaacs <i@izs.me> | 2011-09-13 10:59:42 -0700 |
commit | dc8f4eed53bdf0280de105338523befb99aa0b0d (patch) | |
tree | c1bde0607d512c9ff231e4a66a4629ac30ce90f6 /doc/api/modules.markdown | |
parent | cb6b9eb19e68556be5b21aba8b5542b5b4b7da2d (diff) | |
download | node-new-dc8f4eed53bdf0280de105338523befb99aa0b0d.tar.gz |
Fix #1694 Document require() cycles
Diffstat (limited to 'doc/api/modules.markdown')
-rw-r--r-- | doc/api/modules.markdown | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/doc/api/modules.markdown b/doc/api/modules.markdown index ff73933d50..e0793c5afd 100644 --- a/doc/api/modules.markdown +++ b/doc/api/modules.markdown @@ -30,6 +30,60 @@ Variables local to the module will be private. In this example the variable `PI` is private to `circle.js`. +### Cycles + +When there are circular `require()` calls, a module might not be +done being executed when it is returned. + +Consider this situation: + +`a.js`: + + console.log('a starting'); + exports.done = false; + var b = require('./b.js'); + console.log('in a, b.done = %j', b.done); + exports.done = true; + console.log('a done'); + +`b.js`: + + console.log('b starting'); + exports.done = false; + var a = require('./a.js'); + console.log('in b, a.done = %j', a.done); + exports.done = true; + console.log('b done'); + +`main.js`: + + console.log('main starting'); + var a = require('./a.js'); + var b = require('./b.js'); + console.log('in main, a.done=%j, b.done=%j', a.done, b.done); + +When `main.js` loads `a.js`, then `a.js` in turn loads `b.js`. At that +point, `b.js` tries to load `a.js`. In order to prevent an infinite +loop an **unfinished copy** of the `a.js` exports object is returned to the +`b.js` module. `b.js` then finishes loading, and its exports object is +provided to the `a.js` module. + +By the time `main.js` has loaded both modules, they're both finished. +The output of this program would thus be: + + $ node main.js + main starting + a starting + b starting + in b, a.done = false + b done + in a, b.done = true + a done + in main, a.done=true, b.done=true + +If you have cyclic module dependencies in your program, make sure to +plan accordingly. + ### Core Modules Node has several modules compiled into the binary. These modules are |