Node.js Modules

A module is a collection of code located in a file. In this article, we will learn how to include and export a module.

I. Include modules

require() can be used to import many different types of modules.

For example:

  • Import core modules/packages.
  • Import npm modules/packages.
  • Import a single file in a project.
  • Import single JSON files.
  • Import folders in a project (an alias for importing an index.js in that folder).
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

II. Export modules

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.

1. Export a single property

// 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 ]

2. Export more than 1 property

// 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' ] }

3. Destructuring

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' ]