Node.
js
What is Node.js?
Node.js is an open-source server environment
Node.js is free
Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
Node.js uses JavaScript on the server
What Can Node.js Do?
Node.js can generate dynamic page content
Node.js can create, open, read, write, delete, and close files on the server
Node.js can collect form data
Node.js can add, delete, modify data in your database
What is a Node.js File?
Node.js files contain tasks that will be executed on certain events
A typical event is someone trying to access a port on the server
Node.js files must be initiated on the server before having any effect
Node.js files have extension ".js"
Node.js Basics
Node.js supports JavaScript.
Primitive Types
Node.js includes following primitive types:
String
Number
Boolean
Undefined
Null
RegExp
Everything else is an object in Node.js.
Buffer
Node.js includes an additional data type called Buffer (not available in browser's JavaScript).
Buffer is mainly used to store binary data, while reading from a file or receiving packets over the
network.
Node.js Module
A module is a collection of JavaScript code which encapsulate related code into single unit of code.
Node.js has a simple module loading system. A developer can load a JavaScript library or module into his
program by using require method as given below:
let http = require('http');
Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript
files which can be reused throughout the Node.js application.
Each module in Node.js has its own context, so it cannot interfere with other modules or
pollute global scope. Also, each module can be placed in a separate .js file under a separate
folder.
Node.js Module Types
Node.js includes three types of modules:
1. Core Modules
2. Local Modules
3. Third Party Modules
Core Modules
In Node.js, core modules are built-in modules that are included in the Node.js distribution. These
modules provide basic functionality that is essential for building Node.js applications.
Core modules can be loaded using the require() function without the need for any additional
installation or configuration.
They are categorized into two types:
System/Core Modules:
External Modules:
The following table lists some of the important core modules in Node.js.
Core
Description
Module
It is used to create Http server and Http client. It can be accessed with
http
require('http').
url url module includes methods for URL resolution and parsing.
querystring querystring module includes methods to deal with query string.
path path module includes methods to deal with file paths.
fs It is used to perform operations on files. It can be accessed with require('fs').
It is used to perform operations on raw bytes of data which reside in memory. It
Buffer
can be accessed with require('buffer').
Create file using ‘fs’
const fs=require('fs');
fs.writeFileSync("Malik.js", " I live in Lahore");
Access it through this->
PS C:\Xamp\htdocs\Node> node .\index.js
File has been created successfully
dirname: (Check the directory)
This helps to find the name of the directory by using the dirname function
Syntax:
const fs=require(‘fs’);
console.log(‘__dirname’);
filename: (Check the file name)
Syntax:
const fs=require(‘fs’);
console.log(‘__filename’);
2. External Modules:
External modules are third-party modules that are not included in the Node.js core
distribution, and you need to install them separately using the Node Package Manager
(npm). Some popular external modules include:
Express: a web application framework that simplifies building web applications in
Node.js
Mongoose: an Object Data Modeling (ODM) library for MongoDB and Node.js
Lodash: a utility library that provides a set of functions for common programming tasks.
Global Modules:
Global modules are modules that are installed globally on your system using the Node Package
Manager (npm). These modules can be used in any project or application on your system,
regardless of where they are stored. Like console.log().
We don’t need to use any other function to use that module and we can access it by simply because it is
a global module.
Local Modules:
Local modules are modules that are specific to a particular project or application. These modules are
created by the developer and are stored within the project directory.
To use a local module in Node.js, you need to provide the file path of the module using require()
function. For example, if you have a module named "example.js" located in the same directory as
your main Node.js file, you can load it using the following code:
Example:
let example = require('./example');
Local modules are specific to a project and are installed locally, while global modules can be
used in any project and are installed globally.
http (Hypertext Transfer Protocol)
In Node.js, http is a core module that provides functionality to create HTTP servers and clients.
Using the http module, you can create a web server that listens for incoming HTTP requests and
returns responses to those requests. You can also create an HTTP client that sends HTTP
requests to a server and receives responses.
Const http=require(‘http’)
Const server=http.createServer((req,res)=> {
If(req.url===’/’){
res.write(‘Hello world’);
res.end();
}
});
server.listen(4000);
console.log(“How are you Bilal’);
Package.json
In Node.js, package.json is a file that is used to describe a Node.js package/module. It contains
important information about the package, such as its name, version, dependencies, and other
metadata.
Here's an overview of some of the key information that can be found in a package.json file:
name: The name of the package/module
version: The version number of the package/module
description: A brief description of the package/module
main: The main entry point for the package/module
dependencies: A list of packages/modules that the package/module depends on
devDependencies: A list of packages/modules that are only required for development
scripts: A set of scripts that can be run to perform various tasks, such as testing or
building the package/module
author: The author of the package/module
license: The license under which the package/module is distributed
The package.json file is used by the npm (Node Package Manager) to manage
packages/modules and their dependencies. It can also be used to automate various tasks, such
as running tests, building the package/module, and deploying it to a production environment.
Loading Core Modules:
In order to use Node.js core or NPM modules, you first need to import it using require() function
as shown below.
let module = require('module_name');
As per above syntax, specify the module name in the require() function. The require() function
will return an object, function, property or any other JavaScript type, depending on what the
specified module returns.
The following example demonstrates how to use Node.js http module to create a web server.
Example: Load and Use Core http Module
var http = require('http');
var server = http.createServer(function(req, res){
//write code here
});
server.listen(5000);
In the above example, require() function returns an object because http module returns its
functionality as an object, you can then use its properties and methods using dot notation e.g.
http.createServer().
Node.js Local Module
Local modules are modules created locally in your Node.js application. These modules include
different functionalities of your application in separate files and folders. You can also package it
and distribute it via NPM, so that Node.js community can use it. For example, if you need to
connect to MongoDB and fetch data then you can create a module for it, which can be reused in
your application.
Writing Simple Module
Let's write simple logging module which logs the information, warning or error to the console.
In Node.js, module should be placed in a separate JavaScript file. So, create a Log.js file and
write the following code in it.
Log.js
let log = {
info: function (info) {
console.log('Info: ' + info);
},
warning:function (warning) {
console.log('Warning: ' + warning);
},
error:function (error) {
console.log('Error: ' + error);
}
};
module.exports = log
In the above example of logging module, we have created an object with three functions - info(),
warning() and error(). At the end, we have assigned this object to module.exports. The
module.exports in the above example exposes a log object as a module.
The module.exports is a special object which is included in every JS file in the Node.js
application by default. Use module.exports or exports to expose a function, object or variable
as a module in Node.js.
Now, let's see how to use the above logging module in our application.
Loading Local Module
To use local modules in your application, you need to load it using require() function in the same
way as core module. However, you need to specify the path of JavaScript file of the module.
The following example demonstrates how to use the above logging module contained in Log.js.
app.js
var myLogModule = require('./Log.js');
myLogModule.info('Node.js started');
In the above example, app.js is using log module. First, it loads the logging module using
require() function and specified path where logging module is stored. Logging module is
contained in Log.js file in the root folder. So, we have specified the path './Log.js' in the require()
function. The '.' denotes a root folder.
The require() function returns a log object because logging module exposes an object in Log.js
using module.exports. So now you can use logging module as an object and call any of its
function using dot notation e.g myLogModule.info() or myLogModule.warning() or
myLogModule.error()
Run the above example using command prompt (in Windows) as shown below.
Output
Info: Node.js started
Export Module in Node.js
The module.exports is a special object which is included in every JavaScript file in the Node.js
application by default. The module is a variable that represents the current module, and exports
is an object that will be exposed as a module.
You can save anything in the export module by using module.exports function.
When you have to call that module { module.exports}, you can call it by require.
Example:
App.js
module.exports = 'Hello world';
Now, import this message module and use it as written below.
Index.js
var msg = require('./Message.js');
console.log(msg);
Output:
Hello world
Note:
You must specify ./ as a path of root folder to import a local module. However, you do not need
to specify the path to import Node.js core modules or NPM modules in the require() function.
Export Object
The exports is an object. So, you can attach properties or methods to it. The following
example exposes an object with a string property in app.js file.
Example
app.js
exports.SimpleMessage = 'Hello world';
//or
module.exports.SimpleMessage = 'Hello world';
In the above example, we have attached a property SimpleMessage to the exports object. Now,
import and use this module, as shown below.
Index.js
var msg = require('./Messages.js');
console.log(msg.SimpleMessage);
Output
Hello World
NPM - Node Package Manager
Node Package Manager (NPM) is a command line tool that installs, updates or uninstalls Node.js
packages in your application. It is also an online repository for open-source Node.js packages.
The node community around the world creates useful modules and publishes them as packages in
this repository.
Node.js File System
Node.js includes fs module to access physical file system. The fs module is responsible for all
the asynchronous or synchronous file I/O operations.
Reading a File
Use the fs.readFile() method to read the physical file asynchronously.
Syntax:
fs.readFile(fileName [,options], callback)