Modules

You develop Node.js code in separate files, called modules. There are three module types:

  • Core modules, which you can load anywhere
  • Dependency modules, which you can also load anywhere
  • Local modules, which you need to load based on the relative path

Modules are loaded synchronously and cached. So, a repeated load will actually not be a load; instead, Node.js will pass you a reference to the already loaded module. This is true for all three types of modules:

# loading a JSON file with settings from same path as module
const settings = require("./settings");

Local modules are simple files where you need to know the relative or full path. You can also load a path and Node.js will look up the index.js file inside it. You can also load JSON files. You don't need to specify the file extension since Node.js will look for .js and .json files.

A module is nothing more than an object. The module developers decide what to expose and what not to. When you load a module, the code inside can have timers and I/O operations just like your own code. Even without you initializing it, it can run immediately after you load it.

There are hundreds of thousands of modules available. Take some time to search for something you need instead of writing one of your own. Some modules are structured so you can load parts of it (like async and lodash), thereby avoiding the memory footprint of loading everything when you just need a function or two.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset