0
0
NodejsHow-ToBeginner · 3 min read

How to Use require in Node.js: Syntax and Examples

In Node.js, use require to import modules or files by passing the module name or path as a string. It loads and returns the exported content, allowing you to use functions, objects, or values from other files or packages.
📐

Syntax

The require function takes a single string argument that specifies the module or file to load. It returns the exported content from that module.

  • require('module-name'): Loads a core or installed package module.
  • require('./file-path'): Loads a local file relative to the current file.
  • The returned value is whatever the module exports, usually an object, function, or value.
javascript
const module = require('module-name');
const localFile = require('./local-file');
💻

Example

This example shows how to use require to import a local module that exports a function, then call that function.

javascript
// greet.js
function greet(name) {
  return `Hello, ${name}!`;
}

module.exports = greet;

// app.js
const greet = require('./greet');

console.log(greet('Alice'));
Output
Hello, Alice!
⚠️

Common Pitfalls

Common mistakes when using require include:

  • Forgetting the relative path prefix ./ or ../ when loading local files, which causes Node.js to look for a core or installed module instead.
  • Not exporting anything from the required file, resulting in undefined.
  • Using require with ES modules (.mjs or type: module), which requires import instead.
javascript
// Wrong: missing './' for local file
// const greet = require('greet'); // Error: Cannot find module 'greet'

// Right:
const greet = require('./greet');
📊

Quick Reference

UsageDescriptionExample
Load core moduleImports built-in Node.js modulesconst fs = require('fs');
Load installed packageImports packages from node_modulesconst express = require('express');
Load local fileImports local files with relative pathconst utils = require('./utils');
Export from moduleExpose functions or datamodule.exports = function() { ... };

Key Takeaways

Use require('module-name') to load core or installed modules.
Use require('./file-path') with relative paths for local files.
Always export content in the required file using module.exports.
Require does not work with ES modules; use import for those.
Missing './' for local files causes module not found errors.