How to include Functions from other files in Node.js ?

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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 };

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

//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);

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.