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
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github