a shot of dev knowledge

RELATED TAGS

Creating a private module in Node.js

The Node.js module is a JavaScript file that has objects, functions, and executables, which are all kept in a file.

Module creation is one possible way to get better at learning nodes because you can break your software into respective modules and attach the global exports object to make it available for use in other application development projects.

Modules can also be seen as libraries in terms of programming languages. You can see them as several defined functions that one can include in application development. Though we have built-in modules in Node.js, you can create your own private module with the steps below.

Creating the module

First, for us to create the private module, we need the built-in exports property to make the module available for public or further use in other development tasks.
Go to the Node terminal and create a folder.

$ mkdir newModule

Now, we change the directory to the new module we created.

$ cd newModule

We can define the package.json file of the module.

$ npm init -Y

The package.json file can now appear on the folder we initially created. We update the name and description for the module.


{
  "name": "newModule",
  "version": "1.0.0",
  "description": "A new module to check o latest time and date",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": ["express"],
  "author": "alvan",
  "license": "ISC"
}

We now create, say, a date and time module for instance. Create a newModule.js file in the folder and input the code below.

exports.myDateTime = function(){
    return Date();
};

The module is ready. We now proceed to create the Node project that will need the module.

We create an app.js file to enable us to use our new module.

const http = require('http');
const pt = require('./newModule');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write("The output for my first module is: " + pt.myDateTime());
  res.end();
  console.log("The output for my first module is: " + pt.myDateTime());
}).listen(9090);

From the code above, we can see that the output can be seen on the 9090 port as well as on the Node terminal.

Conclusion

Creating private Node modules is one fast way to hasten your learning approach with rhythm. One can break a big application project into smaller modules and make it work in bits.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring