In Node.js, how do I "include" functions from my other files?

Better Stack Team
Updated on March 11, 2024

In Node.js, you can include (import) functions from other files using the require statement. Here's an example of how to include functions from another file:

Suppose you have a file named mathFunctions.js with some functions:

 
// mathFunctions.js

function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

module.exports = {
  add,
  subtract
};

Now, in another file (let's call it app.js), you can include and use these functions:

 
// app.js

// Include (require) the mathFunctions module
const mathFunctions = require('./mathFunctions');

// Use the functions from mathFunctions module
const resultAdd = mathFunctions.add(5, 3);
const resultSubtract = mathFunctions.subtract(8, 3);

// Log the results
console.log('Addition:', resultAdd);
console.log('Subtraction:', resultSubtract);

In the example above:

  • require('./mathFunctions') is used to import the module defined in mathFunctions.js. The ./ indicates that the module is in the same directory.
  • The imported module is assigned to the variable mathFunctions.
  • You can then use the functions from mathFunctions as if they were defined in the current file.

When you run app.js, it will output:

 
Addition: 8
Subtraction: 5

Remember to replace the file paths with the correct paths in your actual project. The module.exports statement in mathFunctions.js is used to export the functions from that file, making them accessible in other files that require it.

Note: With the introduction of ECMAScript modules (ESM) in newer versions of Node.js (v13.2.0 and later), you can also use import and export syntax. However, the CommonJS require and module.exports syntax is still widely used in many Node.js projects.