EN
Node.js - create custom modules
3
points
In this article, we would like to show you how to create custom modules in Node.js.
Note: below solution will help you to split your JavaScript project into multiple files.
Simple steps:
- Create module file with some logic and use predefined
exports
object to make it available from outside of the module.
ExamplemyModule.js
file content:exports.myFunction = function () { console.log('Message from myFunction.'); } // Put more exports here ...
Note: you can export multiple functions and objects from
myModule.js
. - Import the module inside another JavaScript file using
require()
, so you can use the function.
Exampleindex.js
file content:const myModule = require('./myModule.js'); myModule.myFunction();
Note: address your local modules / files always with
./
prefix - with relative paths. -
Run
index.js
file using Node.js.
Execute the command:node ./index.js
Output:
Message from myFunction.
Project structure
app/
├── index.js
└── myModule.js