Node.js 101: Requiring modules

zenulabidin profile image Ali Sherief ・2 min read

Sooner or later in your journey through Node.js, you will want to make use of the code other people wrote instead of writing everything yourself, so you will look for what we call modules. Think of them as toolboxes that contain tools for building one category of programs.

You might also wish to separate your program and code into separate files so as to not jumble them up in a single file. This raises the question: How do we import variables in other files to another file?

The answer is by using require.

About require

require is a function that takes a string that resembles a file path or a module name, and returns the variables that were exported in them. It is called like require('foo') for a module called foo.js, or require('/home/Documents/myNodeProject/foo.js') for a file called foo.js in the directory in the example.

The way require works is by inspecting the file you are trying to import, or the index.js file of the module you want to import, and it looks for a line that has:

module.exports = ...

The value that is assigned to module.exports is the value that require will set its variable to. Usually module.exports is a single function, or a dictionary of variables and functions such as this one:

// contents of example.js
module.exports = {
  foo: function () {
    // whatever
  bar: function () {
    // whatever

If you save example.js in the current folder, then when you import it from another file, you will be able to access foo and bar:

const example = require('./example.js');


I imported a module with require but it returns undefined

This is by design. require does not return any value, but it sets the variable that you're assigning to be the contents of the exported module. So if you use the variable then it will contain a real value.

> const express = require('express');
// Using the variable returned in 'express'
> var app = express()

I get the error ReferenceError: <name> is not defined

(where <name> is whatever you're trying to import) If you are trying to import a module, then it is neither in the local node_modules folder, or the global system-wide node_modules folder. You might need to install the module with npm. If you're trying to import a file, then check the path to make sure it exists.

Posted on Jun 1 by:

zenulabidin profile

Ali Sherief


Backend developer by trade, frontend developer in the works. He/Him.


markdown guide