nodejs module

  • Node.js has several modules compiled into the binary, such as http
  • Modules are cached after the first time they are loaded.
    • Multiple calls to require('foo') may not cause the module code to be executed multiple times
    • If you want to have a module execute code multiple times, then export a function, and call that function.
  • If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions: .js, .json, and finally .node.
  • When a file is run directly from Node.js, require.main is set to its module. That means that you can determine whether a file has been run directly by testing
    require.main === module
  • exports
    • 一个模块可以通过module.exports或exports将函数、变量等导出,以使其它JavaScript脚本通过require()函数引入并使用
    • 如果运行时让exports、this和module.exports指向不同的对象,只有module.exports指向的对象才回被导出。module.exports才是真正的接口,exports只不过是它的一个辅助工具。 最终返回给调用的是module.exports而不是exports。 所有的exports收集到的属性和方法,都赋值给了module.exports。
    • 如果,Module.exports已经具备一些属性和方法,那么exports收集来的信息将被忽略。
    • exports and module.exports reference the same object
  • exports 的写法
    • 可以是函数
      • = function(x){…};
    • 可以是promise
      • exports.area = (r) => PI * r * r;


This entry was posted in Nodejs. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s