How to use External Modules and NPM in a project ?
Types of Node modules: Module in Node.js is a simple or complex functionality organized into single or multiple JS files which can be used again throughout the Node.js application. There are three types of Node.js modules:
- Local/File-based modules: It define the Node modules within a file in our application and is used within our application.
- Core modules: The core modules are inbuilt modules in Node.js. These modules provide sufficient functionality so that external module designers can add in their own functionality that can be used while developing Node applications. The core modules include path, file system, os, util, and a few others.
- Third-party modules: Third-party modules are the external Node modules. These are the third-party Node modules developed by Node developers that are made available through the Node ecosystem. But we need a package manager that maintains all the modules so that they can be accessed with ease. This is where NPM comes into the picture.
How to export Modules ?
First, initialize a node.js application by typing in npm init in the command prompt/terminal (make sure you are present in the current project folder). It will create a package.json file.
Use the following syntax to add a module in Node.js project.
var module = require("module_name");
Creating own modules and using it: First, initialize node in a directory by typing npm init in the command prompt/terminal.
- Creating a Node.js module (rectange.js):
- Using the Node module in your application (module.js):
- Initializing the main file (index.js):
Please Login to comment...