Introduction to NodeJS and Expressupdated
Introduction to NodeJS and Expressupdated
23CAH-705
BOOKS
Learning Node.js Development Andrew Mead 1st edition Pockt
2018
Node.js in Action Tim Oxley, Nathan Rajlich, TJ Holowaychuk,
Alex Yo,1, Manning 2017
Professional Node.js Pedro Teixeira 1 Wiley 2012
Practical Node.Js: Building Real-World Scalable Web Apps by
Azat Mardan second edition Aprex 2022
COURSE OUTCOMES
CO1 Understand the architecture and design principles of back-end
systems, including APIs, web services, and serverless computing
CO2 Apply the knowledge and skills acquired to develop and deploy back-
end applications, using tools such as Node.js
CO3 Understand the working of Git to upload the created project
C:\Users\Your Name>_
Initiate the Node.js File
The file you have just created must be initiated by Node.js
before any action can take place.
Start your command line interface, write node myfirst.js,
and hit enter:
Initiate "myfirst.js":
C:\Users\Your Name>node myfirst.js
Mathematical expression
Example: >10+20-5
output 25
NODE.jS REPL
you can use npm ls command to list down all the locally
installed modules.
open the node.js command prompt and execute "npm ls":
UNINSTALLING A MODULE
Example own
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');
If the response from the HTTP server is supposed to be displayed as HTML, you should
include an HTTP header with the correct content type:
Exhttpheader.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello World!');
res.end();
}).listen(8080);
The first argument of the res.writeHead() method is the status code, 200 means that all is OK,
the second argument is an object containing the response headers.
READ THE QUERY STRING
The function passed into the http.createServer() has a req argument that
represents the request from the client, as an object (http.IncomingMessage
object).
This object has a property called "url" which holds the part of the url that
comes after the domain name:
Exhttp_url.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(req.url);
res.end();
}).listen(8080);
SPLIT THE QUERY STRING
there are built-in modules to easily split the query string into readable parts, such as the
url module.
split the query string into readable parts:
var http = require('http');
var url = require('url');
The Node.js file system module allows you to work with the file
system on your computer.
To include the File System module, use the require() method:
var fs = require('fs');
Common use for the File System module:
•Read files
•Create files
•Update files
•Delete files
•Rename files
READ FILES
The fs.readFile() method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder as Node.js):
var fs = require('fs');
fs.appendfile('mynewfile1.txt', 'hello content!', function (err) {
if (err) throw err;
console.log('saved!');
});
OPENING A FILE
The fs.open() method takes a "flag" as the second argument, if the flag
is "w" for "writing", the specified file is opened for writing. If the file
does not exist, an empty file is created:
Example
Create a new, empty file using the open() method:
var fs = require('fs');
fs.open('mynewfile2.txt', 'w', function (err, file) {
if (err) throw err;
console.log('Saved!');
});
WRITE FILE
Example
Rename "mynewfile1.txt" to "myrenamedfile.txt":
var fs = require('fs');
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (
err) {
if (err) throw err;
console.log('File Renamed!');
});
THE FORMIDABLE MODULE
there is a very good module for working with file uploads, called
"formidable".
the formidable module can be downloaded and installed using npm:
npm install formidable
after you have downloaded the formidable module, you can include the
module in any application:
var formidable = require('formidable');
UPLOAD FILES
now you are ready to make a web page in node.js that lets the user upload
files to your computer:
step 1: create an upload form
create a node.js file that writes an html form, with an upload field:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post"
enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}).listen(8080);
STEP 2: PARSE THE UPLOADED FILE
include the formidable module to be able to parse the uploaded file once it reaches the server.
when the file is uploaded and parsed, it gets placed on a temporary folder on your computer.
var http = require('http');
var formidable = require('formidable');
var fs = require("fs");
console.log("Program Ended");
CHAINING THE STREAMS
console.log("File Compressed.");
DECOMPRESSING
var fs = require("fs");
var zlib = require('zlib');
console.log("File Decompressed.");
WHAT IS CALLBACK?
callback is an asynchronous equivalent for a function. a callback
function is called at the completion of a given task. node makes
heavy use of callbacks. all the apis of node are written in such a way
that they support callbacks.
for example, a function to read a file may start reading file and return
the control to the execution environment immediately so that the
next instruction can be executed. once file i/o is complete, it will call
the callback function while passing the callback function, the content
of the file as a parameter. so there is no blocking or wait for file i/o.
this makes node.js highly scalable, as it can process a high number
of requests without waiting for any function to return results.
BLOCKING CODE EXAMPLE
I hear a scream!
UTILITY MODULES
there are several utility modules available in node.js module library.
these modules are very common and are frequently used while
developing any node based application.
Syntax:
2 Path Module Provides utilities for handling and transforming file paths.
3 Net Module Provides both servers and clients as streams. Acts as a network
wrapper.
// Require path
const path = require('path');
// Display Resolve
console.log('resolve:' + path.resolve('paths.js'));
// Display Extension
console.log('extension:' + path.extname('paths.js'));
DNS MODULE
dns module enables us to use the underlying operating system name
resolution functionalities. the actual dns lookup is also performed by the
dns module. this dns module provides an asynchronous network wrapper.
the dns module can be imported using the below syntax.
// Require dns module
const dns = require('dns');
// Store the web address
const website = 'www.cuchd.in
// Call lookup function of DNS
dns.lookup(website, (err, address, family) => {
console.log('Address of %s is %j family: IPv%s’, website, address,
family);
});
NET MODULE
net module in node.js is used for the creation of both client and server.
similar to dns module this module also provides an asynchronous network
wrapper.
// Require net module
const net = require('net');
const server = net.createServer(function (connection) {
console.log('client connected'); connection.on('end', function () {
console.log('client disconnected');
});
connection.write('Hello World!\r\n'); connection.pipe(connection);
});
server.listen(8080, function () {
console.log('server listening');
});
const net = require('net');
const client = net.connect(8124, function () {
console.log('Client Connected');
client.write(‘Chandigarh University\r\n');
});
client.on('data', function (data) {
console.log(data.toString());
client.end();
});
client.on('end', function () {
console.log('Server Disconnected');
});
DOMAIN MODULE:
The domain class in the domain module provides a mechanism for routing
the unhandled exceptions and errors to the active domain object. It is
considered to be the child class of EventEmitter.
Syntax:
const domain = require('domain’);
const child = domain.create();
const EventEmitter = require("events").EventEmitter;
const domain = require("domain");
const emit_a = new EventEmitter();
const dom_a = domain.create();
dom_a.on('error', function (err) {
console.log("Error handled by dom_a (" + err.message + ")");
});
dom_a.add(emit_a);
emit_a.on('error', function (err) {
console.log("listener handled this error (" + err.message + ")");
});
emit_a.emit('error', new Error('Listener handles this'));
emit_a.removeAllListeners('error');
emit_a.emit('error', new Error('Dom_a handles this'));
const dom_b = domain.create();
dom_b.on('error', function (err) {
console.log("Error handled by dom_b (" + err.message + ")");
});
dom_b.run(function () {
const emit_b = new EventEmitter();
emit_b.emit('error', new Error('Dom_b handles this'));
});
dom_a.remove(emit_a);
emit_a.emit('error', new Error('Exception message...!'));