Languages
[Edit]
EN

Node.js - create custom modules

3 points
Created by:
Palus-Bear
1016

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 with 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.
  2. 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.

  3. Run index.js file using Node.js.
    Execute the command:

    node ./index.js

    Output:

    Message from myFunction.

 

Project structure

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

References

Alternative titles

  1. Node.js - create your own modules
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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