Ticker

6/recent/ticker-posts

Export Modules in Node.js

Export Modules in Node.js

Introduction:
Node.js allows you to modularize your code by using export and import statements, making it easier to organize and reuse code across multiple files. Exporting modules in Node.js involves defining functions, variables, or classes in one file and making them available for use in other files.

Exporting Modules:

  1. Exporting Functions:
    To export a function from a file, use the exports object or the module.exports object. Here's an example:
javascript
// math.js
exports.add = function(a, b) {
return a + b;
};

exports.subtract = function(a, b) {
return a - b;
};
  1. Exporting Variables:
    You can export variables directly using the exports object or the module.exports object:
javascript
// constants.js
exports.PI = 3.14159;
exports.GRAVITY = 9.81;
  1. Exporting Classes:
    To export a class, assign it to the exports object:
javascript
// car.js
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}

displayInfo() {
return `${this.make} ${this.model}`;
}
}

exports.Car = Car;

Importing Modules:
After exporting modules from one file, you can import and use them in another file using the require function.

  1. Importing Functions and Variables:
javascript
// app.js
const math = require('./math');

const sum = math.add(5, 3);
const difference = math.subtract(7, 2);

console.log(sum); // Output: 8
console.log(difference); // Output: 5

const constants = require('./constants');

console.log(constants.PI); // Output: 3.14159
console.log(constants.GRAVITY); // Output: 9.81
  1. Importing Classes:
javascript
// main.js
const Car = require('./car');

const myCar = new Car('Toyota', 'Camry');
console.log(myCar.displayInfo()); // Output: Toyota Camry

Conclusion:
Node.js makes it easy to export modules and reuse code across different files. By organizing your code into separate modules, you can create more maintainable and scalable applications. Use the exports and require statements to export and import functions, variables, and classes between files, enabling better code organization and separation of concerns.

Post a Comment

0 Comments