Skip to content

Instantly share code, notes, and snippets.

@soichisumi
Last active September 12, 2018 07:49
Show Gist options
  • Select an option

  • Save soichisumi/dcefdaab4d741176d7c5b2fc239a57a8 to your computer and use it in GitHub Desktop.

Select an option

Save soichisumi/dcefdaab4d741176d7c5b2fc239a57a8 to your computer and use it in GitHub Desktop.
nodejs's require caches the module. the cached result is used for second call of require
console.log(`\tfunc1 top\n`);
module.exports = () => {
console.log(`\tfunc1 function\n`);
}
console.log(`\tfunc2 top\n`);
module.exports = ()=>{
console.log(`\tfunc2 function\n`);
}
console.log(`indexjs top\n`);
console.log(`load func1.`)
const func1_1 = require(`./func1`);
const func1_2 = require(`./func1`);
console.log(`func1 loaded.`)
func1_1();
func1_2();
console.log(`func1 executed.`)
console.log(`load func2.`)
const func2_1 = require(`./func2`);
const func2_2 = require(`./func2`);
console.log(`func2 loaded.`)
func2_1();
func2_2();
console.log(`func2 executed.`)
my_terminal_home % node ../moduleTest/index.js
indexjs top
load func1.
func1 top
func1 loaded.
func1 function
func1 function
func1 executed.
load func2.
func2 top
func2 loaded.
func2 function
func2 function
func2 executed.
@soichisumi
Copy link
Copy Markdown
Author

func1 and func2 called twice, but, the result shows "func1 top" and "func2 top" showed once.

each module is cached by nodejs runtime.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment