This id is usually the full path to the file, but in a REPL session it’s simply. You can check it out in a simple REPL session: ~/learn-node $ nodeĮvery module object gets an id property to identify it. Let me introduce you to the module object. Let me first create a directory to host all the examples using my terminal: mkdir ~/learn-node & cd ~/learn-nodeĪll the commands in the rest of this article will be run from within ~/learn-node. In this article, I’ll attempt to explain with examples these different stages and how they affect the way we write modules in Node. Caching: So that when we require this file again, we don’t go over all the steps another time.Evaluating: This is what the VM eventually does with the loaded code.This is what makes both the require and module objects local to every file we require. Wrapping: To give the file its private scope.Loading: To determine the type of the file content.Resolving: To find the absolute path of the file.When Node invokes that require() function with a local file path as the function’s only argument, Node goes through the following sequence of steps: The main object exported by the require module is a function (as used in the above example). Requiring a module in Node isn’t that complicated of a concept. You can think of the require module as the command and the module module as the organizer of all required modules. The module module, which also appears to be available on the global scope - no need to require('module').The require module, which appears to be available on the global scope - no need to require('require').
Node uses two core modules for managing module dependencies: Read the updated version of this content and more about Node at /node-beyond-basics. Update: This article is now part of my book “Node.js Beyond The Basics”.