0% found this document useful (0 votes)
8 views

Nodejs

Uploaded by

areebabatool5533
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Nodejs

Uploaded by

areebabatool5533
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Node – Working with

Modules, Events Module,


Event Emitter Class
Introduction
• Node.js is an open-source and cross-platform JavaScript runtime
environment.
• Node.js runs the V8 JavaScript engine, the core of Google Chrome,
outside of the browser. This allows Node.js to be very performant.
• A Node.js app runs in a single process, without creating a new thread
for every request. Node.js provides a set of asynchronous I/O
primitives in its standard library that prevent JavaScript code from
blocking and generally, libraries in Node.js are written using non-
blocking paradigms, making blocking behavior the exception rather
than the norm.
• When Node.js performs an I/O operation, like reading from the
network, accessing a database or the filesystem, instead of blocking the
thread and wasting CPU cycles waiting, Node.js will resume the
operations when the response comes back.
• This allows Node.js to handle thousands of concurrent connections with
a single server without introducing the burden of managing thread
concurrency, which could be a significant source of bugs.
• Node.js has a unique advantage because millions of frontend
developers that write JavaScript for the browser are now able to write
the server-side code in addition to the client-side code without the
need to learn a completely different language.
Example of Node.js program

const { createServer } = require('node:http');


const hostname = '127.0.0.1';
const port = 3000;
const server = createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
• To run this snippet, save it as a server.js file and run node server.js in your terminal.
• This code first includes the Node.js http module.
• The createServer() method of http creates a new HTTP server and returns it.
• The server is set to listen on the specified port and host name. When the server is
ready, the callback function is called, in this case informing us that the server is
running.
• Whenever a new request is received, the request event is called, providing two
objects: a request (an http.IncomingMessage object) and a response (an
http.ServerResponse object).
• Those 2 objects are essential to handle the HTTP call.
• res.statusCode = 200;
Why node.js

• A common task for a web server can be to open a file on the server
and return the content to the client. Here is how PHP or ASP handles
a file request:
• Sends the task to the computer's file system.
• Waits while the file system opens and reads the file.
• Returns the content to the client.
• Ready to handle the next request.
• how Node.js handles a file request:
• Sends the task to the computer's file system.
• Ready to handle the next request.
• When the file system has opened and read the file, the server returns the
content to the client.
• Node.js eliminates the waiting, and simply continues with the next
request.
• Node.js runs single-threaded, non-blocking, asynchronous
programming, which is very memory efficient.
Why node.js

• 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
Node.JS files

• 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 code
• Once you have downloaded and installed Node.js on your computer, let's
try to display "Hello World" in a web browser.
• Create a Node.js file named "myfirst.js", and add the following code:

var http = require('http');

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
• Save the file on your computer: C:\Users\Your Name\myfirst.js
Initiate the Node.js File

• Node.js files must be initiated in the "Command Line Interface"


program of your computer.
• Start your command line interface, write node myfirst.js and hit enter:
“C:\Users\Your Name>node myfirst.js”
• Now, your computer works as a server!
• If anyone tries to access your computer on port 8080, they will get a
"Hello World!" message in return!
• Start your internet browser, and type in the address:
http://localhost:8080
Node.JS modules
• Modules in Node.js are like libraries in other programming languages.
They help organize and encapsulate code, making it reusable and
maintainable.
• A set of functions you want to include in your application.
• Node.js has a set of built-in modules which you can use without any
further installation.
• Types of Modules
• Core Modules: Built into Node.js (e.g., fs, http, path).
• Local Modules: Custom modules created in your project.
• Third-party Modules: Modules from npm (Node Package Manager).
• To include a module, use the require() function with the name of the
module:
• var http = require('http');
• Now your application has access to the HTTP module, and is able to
create a server:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
• 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:
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“
function greet(name) { return `Hello, ${name}!`;}
module.exports = greet;
• Now you can include and use the module in any of your Node.js files.
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 is 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:
• C:\Users\Your Name>node demo_module.js
• http://localhost:8080
HTTP module

• Node.js has a built-in module called HTTP, which allows Node.js to


transfer data over the Hyper Text Transfer Protocol (HTTP).
• To include the HTTP module, use the require() method:
• var http = require('http');
Node.js as a File Server
• 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):
• <html>
• <body>
• <h1>My Header</h1>
• <p>My paragraph.</p>
• </body>
• </html>
• Create a Node.js file that reads the HTML file, and return the content:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
Path module
• The URL module splits up a web address into readable parts.
• To include the URL module, use the require() method:
• var url = require('url');

• Parse an address with the url.parse() method, and it will return a URL
object with each part of the address as properties:
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);

console.log(q.host); //returns 'localhost:8080'


console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'

var qdata = q.query; //returns an object: { year: 2017, month: 'february' }


console.log(qdata.month); //returns 'february'
What is NPM?

• NPM is a package manager for Node.js packages, or modules if you


like.
• www.npmjs.com hosts thousands of free packages to download and
use.
• The NPM program is installed on your computer when you install
Node.js
Package

• A package in Node.js contains all the files you need for a module.
• Modules are JavaScript libraries you can include in your project.
Download a Package: Open the command line interface and use NPM
to download the package you want.
“C:\Users\Your Name>npm install upper-case”
• NPM creates a folder named "node_modules", where the package
will be placed. All packages you install in the future will be placed in
this folder.
C:\Users\My Name\node_modules\upper-case
Using a Package

• Once the package is installed, it is ready to use.


• Include the "upper-case" package the same way you include any other module:
var uc = require('upper-case');
Create a Node.js file that will convert the output "Hello World!" into upper-case letters:
var http = require('http');
var uc = require('upper-case');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(uc.upperCase("Hello World!"));
res.end();
}).listen(8080);
• C:\Users\Your Name>node demo_uppercase.js
Node.js Events

• Node.js follows an event-driven architecture.


• The events module allows you to work with events and event-driven
programming.
• Every action on a computer is an event. Like when a connection is
made or a file is opened.
• Objects in Node.js can fire events, like the readStream object fires
events when opening and closing a file:
var fs = require('fs');
var rs = fs.createReadStream('./demofile.txt');
rs.on('open', function () {
console.log('The file is open');
});
• Node.js has a built-in module, called "Events", where you can create-, fire-, and
listen for- your own events.
• To include the built-in Events module use the require() method. In addition, all
event properties and methods are an instance of an EventEmitter object. To be
able to access these properties and methods, create an EventEmitter object:
var events = require('events');
var eventEmitter = new events.EventEmitter();
The EventEmitter Object
• You can assign event handlers to your own events with the EventEmitter object
• In the example below we have created a function that will be executed when a "scream"
event is fired.
• To fire an event, use the emit() method.
var events = require('events');
var eventEmitter = new events.EventEmitter();
//Create an event handler:
var myEventHandler = function () {
console.log('I hear a scream!');
}
//Assign the event handler to an event:
eventEmitter.on('scream', myEventHandler);
//Fire the 'scream' event:
eventEmitter.emit('scream');
• 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');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
res.write('File uploaded');
res.end();
});
} else {
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 3: Save the File
• When a file is successfully uploaded to the server, it is placed on a
temporary folder.

• The path to this directory can be found in the "files" object, passed as
the third argument in the parse() method's callback function.

• To move the file to the folder of your choice, use the File System
module, and rename the file:
var http = require('http'); } else {
var formidable = require('formidable');
res.writeHead(200, {'Content-Type':
var fs = require('fs');
'text/html'});
http.createServer(function (req, res) { res.write('<form
if (req.url == '/fileupload') { action="fileupload" method="post"
var form = new formidable.IncomingForm(); enctype="multipart/form-data">');
form.parse(req, function (err, fields, files) { res.write('<input type="file"
var oldpath = files.filetoupload.filepath; name="filetoupload"><br>');
var newpath = 'C:/Users/Your Name/' + res.write('<input type="submit">');
files.filetoupload.originalFilename;
fs.rename(oldpath, newpath, function (err) { res.write('</form>');
if (err) throw err; return res.end();
res.write('File uploaded and moved!');
}
res.end();
}); }).listen(8080);
});

You might also like