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
requirewith ES modules (.mjs ortype: module), which requiresimportinstead.
javascript
// Wrong: missing './' for local file // const greet = require('greet'); // Error: Cannot find module 'greet' // Right: const greet = require('./greet');
Quick Reference
| Usage | Description | Example |
|---|---|---|
| Load core module | Imports built-in Node.js modules | const fs = require('fs'); |
| Load installed package | Imports packages from node_modules | const express = require('express'); |
| Load local file | Imports local files with relative path | const utils = require('./utils'); |
| Export from module | Expose functions or data | module.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.