Node modules in Node JS
Node modules are reusable pieces of code in Node.js, a popular JavaScript runtime environment. They can be used to include various functionalities, like file handling, networking, or database interaction, in your Node.js application. Node modules come in two forms:
1. Core Modules:
- Built into Node.js and can be used without installing anything.
- Examples include:
- fs - used to handle file systems.
- http or https - for creating HTTP(S) servers
- events - used to handle events.
- util - used to handle utility functions e.g deprecate, inspect and format.
- buffer - used to handle binary data.
- stream - used to handle streaming data.
- path - provides utilities for working with file and directory paths. To check out the list of all the other Node.js core modules, check out the official documentation here.
2. External Modules (or Packages):
- Created by the Node.js community and can be installed via npm (Node Package Manager).
- Examples include:
- express for building web applications.
- mongoose for interacting with MongoDB databases.
- lodash for utility functions.
In Node.js, the require
function is used to import modules, JSON files, and other resources into your JavaScript code. It allows you to access functionality defined in other files, which helps organize and modularize your code. Here's a breakdown of how require
works: