0% found this document useful (0 votes)
26 views33 pages

Node.js: Modules and Event Handling Guide

Uploaded by

areebabatool5533
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views33 pages

Node.js: Modules and Event Handling Guide

Uploaded by

areebabatool5533
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Node – Working with

Modules, Events Module,


Event Emitter Class
Introduction
• [Link] is an open-source and cross-platform JavaScript runtime
environment.
• [Link] runs the V8 JavaScript engine, the core of Google Chrome,
outside of the browser. This allows [Link] to be very performant.
• A [Link] app runs in a single process, without creating a new thread
for every request. [Link] provides a set of asynchronous I/O
primitives in its standard library that prevent JavaScript code from
blocking and generally, libraries in [Link] are written using non-
blocking paradigms, making blocking behavior the exception rather
than the norm.
• When [Link] 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, [Link] will resume the
operations when the response comes back.
• This allows [Link] 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.
• [Link] 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 [Link] program

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


const hostname = '[Link]';
const port = 3000;
const server = createServer((req, res) => {
[Link] = 200;
[Link]('Content-Type', 'text/plain');
[Link]('Hello World');
});
[Link](port, hostname, () => {
[Link](`Server running at [Link]
});
• To run this snippet, save it as a [Link] file and run node [Link] in your terminal.
• This code first includes the [Link] 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 [Link] object) and a response (an
[Link] object).
• Those 2 objects are essential to handle the HTTP call.
• [Link] = 200;
Why [Link]

• 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 [Link] 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.
• [Link] eliminates the waiting, and simply continues with the next
request.
• [Link] runs single-threaded, non-blocking, asynchronous
programming, which is very memory efficient.
Why [Link]

• [Link] can generate dynamic page content


• [Link] can create, open, read, write, delete, and close files on the
server
• [Link] can collect form data
• [Link] can add, delete, modify data in your database
[Link] files

• [Link] files contain tasks that will be executed on certain events


• A typical event is someone trying to access a port on the server
• [Link] files must be initiated on the server before having any effect
• [Link] files have extension ".js"
[Link] code
• Once you have downloaded and installed [Link] on your computer, let's
try to display "Hello World" in a web browser.
• Create a [Link] file named "[Link]", and add the following code:

var http = require('http');

[Link](function (req, res) {


[Link](200, {'Content-Type': 'text/html'});
[Link]('Hello World!');
}).listen(8080);
• Save the file on your computer: C:\Users\Your Name\[Link]
Initiate the [Link] File

• [Link] files must be initiated in the "Command Line Interface"


program of your computer.
• Start your command line interface, write node [Link] and hit enter:
“C:\Users\Your Name>node [Link]”
• 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:
[Link]
[Link] modules
• Modules in [Link] 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.
• [Link] has a set of built-in modules which you can use without any
further installation.
• Types of Modules
• Core Modules: Built into [Link] (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:
[Link](function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
[Link]('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:
[Link] = 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 "[Link]“
function greet(name) { return `Hello, ${name}!`;}
[Link] = greet;
• Now you can include and use the module in any of your [Link] files.
var http = require('http');
var dt = require('./myfirstmodule');

[Link](function (req, res) {


[Link](200, {'Content-Type': 'text/html'});
[Link]("The date and time is currently: " + [Link]());
[Link]();
}).listen(8080);
• Notice that we use ./ to locate the module, that means that the
module is located in the same folder as the [Link] file.
• Save the code above in a file called "demo_module.js", and initiate
the file:
• C:\Users\Your Name>node demo_module.js
• [Link]
HTTP module

• [Link] has a built-in module called HTTP, which allows [Link] to


transfer data over the Hyper Text Transfer Protocol (HTTP).
• To include the HTTP module, use the require() method:
• var http = require('http');
[Link] as a File Server
• The [Link] 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 [Link]() method is used to read files on your computer.
• Assume we have the following HTML file (located in the same folder as
[Link]):
• <html>
• <body>
• <h1>My Header</h1>
• <p>My paragraph.</p>
• </body>
• </html>
• Create a [Link] file that reads the HTML file, and return the content:
var http = require('http');
var fs = require('fs');
[Link](function (req, res) {
[Link]('[Link]', function(err, data) {
[Link](200, {'Content-Type': 'text/html'});
[Link](data);
return [Link]();
});
}).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 [Link]() method, and it will return a URL
object with each part of the address as properties:
var url = require('url');
var adr = '[Link]
var q = [Link](adr, true);

[Link]([Link]); //returns 'localhost:8080'


[Link]([Link]); //returns '/[Link]'
[Link]([Link]); //returns '?year=2017&month=february'

var qdata = [Link]; //returns an object: { year: 2017, month: 'february' }


[Link]([Link]); //returns 'february'
What is NPM?

• NPM is a package manager for [Link] packages, or modules if you


like.
• [Link] hosts thousands of free packages to download and
use.
• The NPM program is installed on your computer when you install
[Link]
Package

• A package in [Link] 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 [Link] file that will convert the output "Hello World!" into upper-case letters:
var http = require('http');
var uc = require('upper-case');
[Link](function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
[Link]([Link]("Hello World!"));
[Link]();
}).listen(8080);
• C:\Users\Your Name>node demo_uppercase.js
[Link] Events

• [Link] 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 [Link] can fire events, like the readStream object fires
events when opening and closing a file:
var fs = require('fs');
var rs = [Link]('./[Link]');
[Link]('open', function () {
[Link]('The file is open');
});
• [Link] 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 [Link]();
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 [Link]();
//Create an event handler:
var myEventHandler = function () {
[Link]('I hear a scream!');
}
//Assign the event handler to an event:
[Link]('scream', myEventHandler);
//Fire the 'scream' event:
[Link]('scream');
• make a web page in [Link] that lets the user upload files to your
computer:
Step 1: Create an Upload Form
• Create a [Link] file that writes an HTML form, with an upload field:
• var http = require('http');

[Link](function (req, res) {


[Link](200, {'Content-Type': 'text/html'});
[Link]('<form action="fileupload" method="post" enctype="multipart/form-data">');
[Link]('<input type="file" name="filetoupload"><br>');
[Link]('<input type="submit">');
[Link]('</form>');
return [Link]();
}).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');
[Link](function (req, res) {
if ([Link] == '/fileupload') {
var form = new [Link]();
[Link](req, function (err, fields, files) {
[Link]('File uploaded');
[Link]();
});
} else {
[Link](200, {'Content-Type': 'text/html'});
[Link]('<form action="fileupload" method="post" enctype="multipart/form-data">');
[Link]('<input type="file" name="filetoupload"><br>');
[Link]('<input type="submit">');
[Link]('</form>');
return [Link]();
}}).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');
[Link](200, {'Content-Type':
var fs = require('fs');
'text/html'});
[Link](function (req, res) { [Link]('<form
if ([Link] == '/fileupload') { action="fileupload" method="post"
var form = new [Link](); enctype="multipart/form-data">');
[Link](req, function (err, fields, files) { [Link]('<input type="file"
var oldpath = [Link]; name="filetoupload"><br>');
var newpath = 'C:/Users/Your Name/' + [Link]('<input type="submit">');
[Link];
[Link](oldpath, newpath, function (err) { [Link]('</form>');
if (err) throw err; return [Link]();
[Link]('File uploaded and moved!');
}
[Link]();
}); }).listen(8080);
});

You might also like