Monday, October 5, 2015

Node.js Module

A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file. Node.js has a simple module loading system. In Node.js, files and modules are in one-to-one correspondence. As an example, foo.js loads the module circle.js in the same directory.
The semantics of Node.js's require() function were designed to be general enough to support a number of reasonable directory structures. Package manager programs such as dpkg, rpm, and npm will hopefully find it possible to build native packages from Node.js modules without modification.
Core Modules
Node.js has several modules compiled into the binary. The core modules are defined within Node.js's source and are located in the lib/ folder. Core modules are always preferentially loaded if their identifier is passed to require(). For instance, require('http') will always return the built in HTTP module, even if there is a file by that name.
exports VS. module.exports
  • exports is an alias to module.exports.
  • node automatically creates it as a convenient shortcut.
  • For assigning named properties, use either one.
     > module.exports.fiz = "fiz";
     > exports.buz = "buz";
     > module.exports === exports;
     true

  • Assigning anything to exports directly (instead of exports.something) will overwrite the exports alias.
Named exports - one module, many exported things
Anonymous exports - simpler client interface

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.