Show List

Node.js modules

Node.js modules are a way of organizing and sharing code in Node.js applications. A module in Node.js is a self-contained unit of code that exports specific functionality for use by other parts of the application. For example, you could create a module for database connectivity and use it in multiple parts of your application without having to repeat the code.

Here's an example of how you can use a module in Node.js:

  1. Create a file called "math.js" and add the following code to it:
exports.add = function (a, b) {
  return a + b;
};

exports.subtract = function (a, b) {
  return a - b;
};
  1. In a separate file, such as "app.js", you can use the math.js module like this:
var math = require('./math');

console.log(math.add(1, 2)); // Output: 3
console.log(math.subtract(5, 3)); // Output: 2

Here's an example of how you can use npm to install a package in your Node.js application:

  1. Initialize your Node.js project by running the following command in your terminal:
npm init
  1. Install a package, for example, the "lodash" library, by running the following command:
npm install lodash
  1. You can now use the "lodash" library in your Node.js application by requiring it like this:
var _ = require('lodash');

console.log(_.isArray([1, 2, 3])); // Output: true
In this example, you used npm to install the "lodash" package, and then required it in your Node.js application to use its functions. npm makes it easy to manage the dependencies of your Node.js application and helps you keep your code organized.

    Leave a Comment


  • captcha text