In Node.js, how do I "include" functions from my other files?
In Node.js (CommonJS), you can “include” functions from one file in another by using the require
function and module.exports
. Each file is treated as a separate module. Below is a quick guide on how to export and import (require) functions.
1. Exporting Functions
In one file (let’s call it utils.js
), define your function(s) and assign them to module.exports
or the exports
object. For example:
// utils.js function greet(name) { return `Hello, ${name}!`; } // Export a single function: module.exports = greet; // Or export multiple functions as an object: // module.exports = { greet, anotherFunction };
If you want to export multiple utilities, create and export them as an object:
function greet(name) { return `Hello, ${name}!`; } function farewell(name) { return `Goodbye, ${name}!`; } module.exports = { greet, farewell, };
2. Requiring Functions in Another File
In your main file (let’s call it app.js
), require the module where you defined your function(s). For instance:
// app.js const greet = require('./utils'); // If you exported an object, you might do: // const { greet, farewell } = require('./utils'); console.log(greet('Alice'));
- The relative path (
./utils
) points to the file exporting the function(s). - If you exported multiple functions, destructure the object accordingly.
3. Using ES Modules (Optional Alternative)
In newer versions of Node.js (v12+ in most cases), you can enable ES Modules by setting "type": "module"
in your package.json
or using the .mjs
file extension. Then you can use import
/export
syntax:
{ "type": "module" }
Example of ES Modules
// utils.js (ES module) export function greet(name) { return `Hello, ${name}!`; } // or default export: // export default function greet(name) { ... }
// app.js (ES module) import { greet } from './utils.js'; console.log(greet('Alice'));
Recommended Resource
Summary
- CommonJS (Default in Node.js):
- Export:
module.exports = functionName
or an object. - Import:
const functionName = require('./file')
.
- Export:
- ES Modules (Optional):
- Export:
export function
,export default
, orexport { ... }
. - Import:
import { functionName } from './file.js';
.
- Export:
Use the approach that matches your Node.js setup. For most projects, CommonJS (module.exports
/ require
) is still standard unless you specifically configure "type": "module"
in your package.