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:
Now, in another file (let's call it app.js), you can include and use these functions:
In the example above:
require('./mathFunctions')is used to import the module defined inmathFunctions.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
mathFunctionsas if they were defined in the current file.
When you run app.js, it will output:
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.
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.