Languages
[Edit]
EN

Node.js - create custom modules

3 points
Created by:
Palus-Bear
586

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:

  1. Create module file (e.g. myModule.js).
  2. Inside the file create some logic and use predefined exports object to make it available from outside of the module.
    Example myModule.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.
  3. Import the module inside another JavaScript file using require(), so you can use the function.
    Example index.js file content:
    const myModule = require('./myModule.js');
    
    myModule.myFunction();

    Note: address your local modules / files always with ./ prefix - with relative paths.

    Running:

    node ./index.js

    Output:

    Message from myFunction.

 

Project structure

app/
 ├── index.js
 └── myModule.js

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join