adds code

How do you create your own module in Node.js?

Quick answer: Write functions in a separate file and attach them to the exports object, then load that file from another script with require('./filename'). The ./ prefix tells Node.js the module is a local file in the same folder. The video above demonstrates the classic example: a module that returns the current date and time, consumed by an HTTP server.

What does the exports keyword do?

In CommonJS — Node.js's original module system — every file is a module with its own scope. Nothing inside it is visible to other files until you export it. The line exports.myDateTime = function () { return Date(); }; makes myDateTime callable by any file that requires this module. The official Node.js Modules API documentation defines this contract: module.exports is the object returned by require(), and exports is initially a reference to it.

How do you include your own module in an application?

  1. Save the module: create myfirstmodule.js containing exports.myDateTime = function () { return Date(); };
  2. Create the consumer file demo_module.js:
    var http = require('http');
    var dt = require('./myfirstmodule');
    
    http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write("The date and time are currently: " + dt.myDateTime());
      res.end();
    }).listen(8080);
  3. Run it: node demo_module.js, then open http://localhost:8080.

The require('./myfirstmodule') call resolves to myfirstmodule.js in the same directory — the modules documentation details this resolution algorithm.

CommonJS vs ES modules: which should you use?

FeatureCommonJSES Modules
Syntaxrequire() / exports.x = ...import x from ... / export ...
LoadingSynchronousAsynchronous
File extension / flag.js (default).mjs or "type": "module" in package.json
Where documentedNode.js Modules APINode.js ESM API

New code can use either; countless tutorials (including this video) still use CommonJS, so reading both is essential.

Why does ./ matter in require()?

Without a path prefix, require('myfirstmodule') looks for a package in node_modules — installed via npm. With require('./myfirstmodule'), Node treats it as a local file relative to the current file. The npm docs on packages and modules explain this distinction: packages are directories with a package.json; modules are any loadable file or directory.

Frequently Asked Questions

Can one module export multiple things?

Yes. Attach each function or value to exports separately (exports.a = ...; exports.b = ...;) or replace module.exports wholesale with an object containing everything.

Is require() cached?

Yes. A module's code runs once per application; subsequent require() calls of the same file return the cached exports object, as described in the official modules reference.

Do I need npm to use my own modules?

No. Local modules work with plain Node.js. npm becomes relevant when you want third-party packages or to publish your own.

Why does my module show "undefined" when called?

Usually a missing export: the function was defined but never attached to exports, or the wrong path was passed to require(). Check both lines first.

Sources



How To Create Module | Web application Node Js | Tutorial For Beginner https://youtu.be/nXUdLhoxCbw Create Your Own Modules You can create your own modules, and easily include them in your applications. The following example creates a module that returns a date and time object: Example Create a module that returns the current date and time: exports.myDateTime = function () { return Date(); }; Use the exports keyword to make properties and methods available outside the module file. Save the code above in a file called "myfirstmodule.js" Include Your Own Module Now you can include and use the module in any of your Node.js files. Example Use the module "myfirstmodule" in a Node.js file: var http = require('http'); var dt = require('./myfirstmodule'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write("The date and time are currently: " + dt.myDateTime()); res.end(); }).listen(8080); Notice that we use ./ to locate the module, that means that the module is located in the same folder as the Node.js file. Save the code above in a file called "demo_module.js", and initiate the file: Initiate demo_module.js: C:\Users\Your Name\node demo_module.js If you have followed the same steps on your computer, you will see the same result as the example: http://localhost:8080 Hello World Program | Web application Node Js | Tutorial For Beginner https://youtu.be/gDQ-jU5bo7w Software Installation | Node Js :- https://youtu.be/7gi6lgK-BIA Node Js Download Link:- https://nodejs.org/en/download Software Installation Playlist https://www.youtube.com/playlist?list=PLHeKsaIQNmlqvVEHF9mMfUPMCPtIjlARL #Subscribe the #Channel #Link :- #bansodetechsoluiotn #ajupgrading https://www.youtube.com/c/AjUpgradingBANSODETECHSOLUTION?sub_confirmation=1 IF any #Query or #Doubt #DM on #Instagram :- #bansode_ajay_2102 https://www.instagram.com/bansode_ajay_2102?r=nametag Whatsapp Channel Link https://whatsapp.com/channel/0029VaOllPkEKyZAoy7K791X
Previous Post Next Post