Let's assume you have two files:
-
math.js: This file contains a simple function to add two numbers.
-
app.js: This file will import the math.js functions and use them.
1. Exporting from the first file (math.js)
In the file where you define your functions or variables (math.js in this case), you need to export them using module.exports.
math.js:
// math.js
// Define a function
function add(a, b) {
return a + b;
}
// Export the function so it can be used in other files
module.exports = {
add
};
Here, we are exporting the add function from math.js so that other files can import and use it.
2. Importing in the second file (app.js)
In the file where you want to use the functions from another file (app.js in this case), you import the functions using the require() function.
app.js:
// app.js
// Import the `add` function from the `math.js` file
const math = require('./math');
// Use the imported function
const result = math.add(3, 5);
console.log(`The sum is: ${result}`);
In this file:
-
require('./math') imports the module (i.e., math.js), and the result is assigned to the math variable.
-
We then access the add function from the math module using math.add().