Skip to content
Related Articles

Related Articles

How to include Functions from other files in Node.js ?
  • Difficulty Level : Easy
  • Last Updated : 29 Jun, 2020

Code reusability is an important pillar in modern day programming. Code Reuse means the practice of using an existing code for a new function or software. In this article, we would learn how to use functions from other files in Node.js

This functionality can be easily implemented using the inbuilt export and require functions of Node.js.

Export: The module.exports in Node.js is used to export any literal, function or object as a module. It is used to include JavaScript file into Node.js applications. The module is similar to variable that is used to represent the current module and exports is an object that is exposed as a module.

Require() function: It is an inbuilt function and is the easiest way to include functions that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the export object.

Let us consider the following basic example:



Filename: cal.js




function sum(x, y) {
    return (x + y);
}
  
function sub(x, y) {
    return (x - y);
}
  
function mul(x, y) {
    return (x * y);
}
  
module.exports = { add, sub, mul, div };

In the above example, we use the module.exports function so that we can use it in other files. The functions are enclosed within curly brackets( { } ) according to the format to export multiple functions at a time.

Suppose we wanted to use these functions in main.js, then it can be easily done using the following code:

Filename: main.js




//requiring cal.js file
const cal = require("./cal.js")  
  
//Using the functions from cal.js 
const sum = cal.sum(2, 2);
console.log(sum); 
  
const sub = cal.sub(10, 5);
console.log(sub); 
  
const product = cal.mul(2, 3);
console.log(product);

This will import the cal.js file and its functions into the main.js file.

Run main.js file using the following command:

node main.js

Output:

4
5
6
My Personal Notes arrow_drop_up
Recommended Articles
Page :