🍂 Introduction to Node.js Core Modules🍂
Core Node modules you must know as a Node.js Developer
A module
is any file or directory in the node_modules the directory that can be loaded by the Node.js require()
function😄.
NodeJS is a runtime environment for JavaScript which is built on Chrome’s V8 engine. It runs the JavaScript code outside the browser. Here outside refers to the backend😯
. NodeJS acts as a server-side language.
It comes with various core modules
that extend NodeJS’s functionalities.
Here we are going to discuss built-in modules in Node.js and their uses.🤠 If you want to look into the synchronous way and other file system functionalities, check out 👉this documentation page.
What are Node.js modules?🤷♀️
We can refer to modules as small encapsulated units which can be reused and shared with anyone. Easier to maintain and debug because they are separate pieces of code from each other.
Node.js modules can be categorized into three👌 types core modules, user-created or local modules, and third-party modules
.
- ☝️Core modules — Inbuilt modules in the node.js
- ✌️User-created modules — Modules created by the user
- 👌Third-party modules — Shared modules created and maintained by others
Core modules in Node.js📚
Node js comes with a number of built-in modules that are included with the platform. The required function
can be used to load these modules into the program.
Built-in modules of node.js that are part of nodejs and come with the Node.js installation process are known as core modules
.
To load/include this module in our program, we use the require function
.=>Syntax:
const module = require('module_name');
Depending on what the module returns, the require()
function will return a JavaScript type.
There are lots of core modules out there🤠. Here, I am going to discuss a few of the most important and most used node.js core modules
.
('fs') File System module☝️
The file system module opens the doors to interacting with the file system of your device.
require
are used to consume modules. It allows you to include modules in your programs. You can add built-in core Node.js modules, community-based modules (node_modules), and local modules.
Let’s say we want to read a file from the filesystem. Node has a core module called ‘fs’:
const fs = require('fs');
fs.readFile('./file.txt', 'utf-8', (err, data) => {
if(err) { throw err; }
console.log('data: ', data);
});
As you can see, we imported the “fs”
module into our code. It allows us to use any function attached to it, like “readFile”
and many others.
HTTP Module
It is a built-in module of node.js
. It allows node.js applications to transfer data using HyperText Transfer Protocol (HTTP)
.
This module creates an HTTP server
that listens to server ports and also gives responses back to the client.
CREATE SERVER🚀:
We can use it to create a server. The create server will take a function that will run when we try to access the port.
listen()
starts the HTTP server and listens for connections.The below code sets up a server that we can access when we visit
localhost:3000
Code⌨️ for creating http server:
const http = require('http');
http.createServer(function (req, res) {
res.write('Welcome to Chhakulis Blog!');
res.end();
}).listen(3000);
- If the message from the server needs to be shown as an HTML, then we have to include content type in the header.
Code for adding http header:
const http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<h1>Hello from Chhakulis Blog!</h1>');
res.end();
}).listen(3000);
Explanation of the above code:
- In the first line of code, we load the
http
module and store it in a variable http. - Next,
createServer
is a method that provides the functionality to create a server. It uses a callback method. In the callback method, we have passedreq (request)
andres(response)
. - In the next line, we have set the
status code 200
, to tell the browser, thateverything is OK
. And the data, we have passed in HTML. - Write the text that is passed to the body of the page.
res.end()
→ we write this at the end to tell the server that all response headers and data have been sent.- And at last, we have to tell the server about their
PORT to serve
.
OS Module
The os module
provides a number of operating system-related utility methods.
The os module is a built-in module in Node.js
. This module provides underlying operating-system-related
information using various utility functions and properties.
This module can be imported simply using require() function.
const os = require('os');
console.log(os.freemem()); //free memory available(bytes)
console.log(os.hostname());//host name
console.log(os.homedir());//home directory
console.log("Platform: " + os.platform());
console.log("OS Architecture" + os.arch());
Important Node.js modules and their uses👩🎓
The most used modules are:
fs (file system): It handles the file systems, using this module you can create, read, and open files, etc.
http: It is a mostly used module that makes NodeJS, an http server. Using this module, we will create a server to print the message.
path: It helps to find the file paths.
process: It is a global object and provides information related to the program execution. You do not need to load it using
require()
method.os: It contains the details of the operating system in which the node js application is currently running.
Events: It is used for events handling in node.js. In node.js, events are emitted by other node objects. It can be accessed with
require('events')
.querystring– is a program that parses and formats URL query strings.
url: This module also helps in parsing the urls.
Conclusion🙆♀️
In this blog we discussed what are modules, their types, uses, and also seen the Http, os and fs modules
.
Hope you loved reading 🙋♀️it and don’t forget to check other blogs.