Node.js Exporting and Importing Module in node.js Using a simple module in node.js

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

What is a node.js module (link to article):

A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file.

Now lets see an example. Imagine all files are in same directory:

File: printer.js

"use strict";

exports.printHelloWorld = function (){
    console.log("Hello World!!!");
}

Another way of using modules:

File animals.js

"use strict";

module.exports = {
    lion: function() {
        console.log("ROAARR!!!");
    }

};

File: app.js

Run this file by going to your directory and typing: node app.js

"use strict";

//require('./path/to/module.js') node which module to load
var printer = require('./printer');
var animals = require('./animals');

printer.printHelloWorld(); //prints "Hello World!!!"
animals.lion(); //prints "ROAARR!!!"


Got any Node.js Question?