Getting started with Node.js - kollektivesplagiieren/innovative-commercial-market GitHub Wiki

CommonJS modules

The CommonJS standards specify the following three key components when working with modules:

  • require(): This method is used to load the module into your code.

  • exports: This object is contained in each module and allows you to expose pieces of your code when the module is loaded.

  • module: This object was originally used to provide metadata information about the module. It also contains the pointer of an exports object as a property. However, the popular implementation of the exports object as a standalone object literally changed the use case of the module object.

In Node's CommonJS module implementation, each module is written in a single JavaScript file and has an isolated scope that holds its own variables. The author of the module can expose any functionality through the exports object.

Node.js folder modules

If Node finds a package.json file, it will try parsing it, looking for the main property. Node will try to load the ./<path>/<your-module>.js file. If the package.json file doesn't exist or the main property isn't defined, Node will automatically try to load the ./<path>/index.js file.

Connect middleware

Each middleware function is defined with the following three arguments:

  • req: This is an object that holds the HTTP request information

  • res: This is an object that holds the HTTP response information and allows you to set the response properties

  • next: This is the next middleware function defined in the ordered set of Connect middleware

When you have a middleware defined, you'll just have to register it with the Connect application using the app.use() method.

Understanding the order of Connect middleware

Each Connect middleware function will be executed in first-in-first-out (FIFO) order using the next arguments until there are no more middleware functions to execute or the next middleware function is not called.

Mounting Connect middleware

Connect middleware supports a feature called mounting, which enables you to determine which request path is required for the middleware function to get executed. Mounting is done by adding the path argument to the app. use() method.

⚠️ **GitHub.com Fallback** ⚠️