A module is a collection of code located in a file. In this article, we will learn how to include and export a module.
require()
can be used to import many different types of modules.
For example:
const filesystem = require("fs"); // core module
const express = require("express"); // npm module
const server = require("./server"); // server.js file in the same directory
const server = require("./boot/server"); // server.js file with a relative path down the tree
const server = require("../boot/server"); // server.js file with a relative path up the tree
const server = require("/var/www/app/boot/server"); // server.js file with an absolute path
const routes = require("../routes"); // index.js inside routes folder if there's no routes.js file
const databaseConfigs = require("./configs/database.json"); // JSON file
To export a module, we use the module.exports
keyword.
module.exports allows us to export code to other programs or other files.
Module.exports is a global property and it’s available across your entire file.
// in number.js
const number = [1, 2, 3, 4, 5];
module.exports = number;
// in calculate.js
const data = require("./number");
console.log(data);
// Result: [ 1, 2, 3, 4, 5 ]
// in number.js
const number = [1, 2, 3, 4, 5];
const name = ["anna", "joe", "barry"];
module.exports = { number, name };
// in calculate.js
const data = require("./number");
console.log(data);
// Result: { number: [ 1, 2, 3, 4, 5 ], name: [ 'anna', 'joe', 'barry' ] }
A better way to import multiple things from a different file is destructuring.
The destructuring syntax makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
// in calculate.js
const { number, name } = require("./number");
console.log(number);
console.log(name);
// Result:
// [ 1, 2, 3, 4, 5 ]
// [ 'anna', 'joe', 'barry' ]