What is the purpose of Node.js module.exports and how do you use it?
In Node.js, module.exports
is a special object that is used to define what a module exports as its public interface. It is used to expose functionality from one module (file) to another module, allowing you to encapsulate and organize your code into reusable and maintainable units.
Here's how you can use module.exports
:
Exporting a Single Function or Object:
// math.js
const add = (a, b) => a + b;
module.exports = add;
In another file:
// app.js
const addFunction = require('./math.js');
console.log(addFunction(2, 3)); // Outputs: 5
Exporting Multiple Functions or Objects:
// math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
module.exports = {
add,
subtract
};
In another file:
// app.js
const mathFunctions = require('./math.js');
console.log(mathFunctions.add(2, 3)); // Outputs: 5
console.log(mathFunctions.subtract(5, 3)); // Outputs: 2
Exporting as Named Variables:
// math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
module.exports.add = add;
module.exports.subtract = subtract;
In another file:
// app.js
const mathFunctions = require('./math.js');
console.log(mathFunctions.add(2, 3)); // Outputs: 5
console.log(mathFunctions.subtract(5, 3)); // Outputs: 2
Shorthand for Named Exports:
// math.js
exports.add = (a, b) => a + b;
exports.subtract = (a, b) => a - b;
In another file:
// app.js
const mathFunctions = require('./math.js');
console.log(mathFunctions.add(2, 3)); // Outputs: 5
console.log(mathFunctions.subtract(5, 3)); // Outputs: 2
module.exports
is crucial for organizing code into reusable and manageable modules in Node.js. It allows you to expose specific functions, objects, or variables from a module and make them accessible to other parts of your application.
-
How do you get a list of the names of all files present in a directory in Node.js?
In Node.js, you can use the fs (file system) module to get a list of file names in a directory. Here's an example using the fs.readdir function: const fs = require('fs'); const directoryPath = '/pa...
Questions -
How can I update Node.js and NPM to their latest versions?
There are several ways to update Node.js to its latest version. Here are three methods: Updating Node.js Using NPM You can use NPM to update Node.js by installing the n package, which will be used ...
Questions