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

Web Technologies Unit 5 Part 1

Uploaded by

Syed Sharashree
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)
8 views

Web Technologies Unit 5 Part 1

Uploaded by

Syed Sharashree
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
You are on page 1/ 27

Web Technologies

SERVERLESS AND MOBILE BASED WEB DEVELOPMENT


Node Programming Fundamentals – Asynchronous Programming Techniques – Sequencing
Asynchronous Logic – Node JS – Global Objects – Event Listeners – J2ME Basics – MIDlet
–Mobile Web Application Frameworks – Simple Android Based Development – Cloud Based
Applications Deployment.
Node.js
• Node.js is a cross-platform runtime environment and library for
running JavaScript applications outside the browser.
• It is used for creating server-side and networking web
applications.
• It is open source and free to use.
• Many of the basic modules of Node.js are written in JavaScript.
• Node.js is mostly used to run real-time server applications.
• Node.js is a platform built on Chrome's JavaScript runtime for
easily building fast and scalable network applications.
• Node.js uses an event-driven, non-blocking I/O model that
makes it lightweight and efficient, perfect for data-intensive
real-time applications that run across distributed devices.
• Node.js = Runtime Environment + JavaScript Library
• Node.js runs on various platforms (Windows, Linux, Unix, Mac
OS X, etc.)
Node.js
Node.js uses asynchronous programming!
A common task for a web server can be to open a file on the server and return the content to the client.
How PHP 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.
• 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- Features
some important features of Node.js that makes it the first choice of software architects.
Extremely fast:
Node.js is built on Google Chrome's V8 JavaScript Engine, so its library is very fast in code execution.
I/O is Asynchronous and Event Driven:
All APIs of Node.js library are asynchronous i.e. non-blocking. So a Node.js based server never waits for
an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of
Node.js helps the server to get a response from the previous API call. It is also a reason that it is very fast.
Single threaded:
Node.js follows a single threaded model with event looping.
Highly Scalable:
Node.js is highly scalable because event mechanism helps the server to respond in a non-blocking way.
No buffering:
Node.js cuts down the overall processing time while uploading audio and video files. Node.js
applications never buffer any data. These applications simply output the data in chunks.
Open source:
Node.js has an open source community which has produced many excellent modules to add additional
capabilities to Node.js applications.
License:
Node.js is released under the MIT license.
Node.js Using Netbeans 12
Node.js Using Netbeans 12 Tools->Option
Node.js Using Netbeans 12 Tools->Option
Node.js Using Netbeans 12
Node.js Using Netbeans 12
Node.js Using Netbeans 12
Node.js-web-based Example
node.js web application contains the following three parts:
Import required modules:
• The "require" directive is used to load a Node.js module.
• The first step is to use “require” directive to load http module and store returned HTTP instance into http
variable.
For example: var http = require("http");
Create server:
• Have to establish a server which will listen to client's request similar to Apache HTTP Server.
• created http instance and call http.createServer() method to create server instance and then bind it at port
8085 using listen method associated with server instance.
• Pass it a function with request and response parameters and write the sample implementation to return "Hello
World"
Read request and return response:
Server created in the second step will read HTTP request made by client which can be a browser or console and
return the response.
var http=require("http");
//create server
http.createServer(function(request,response){
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World!!!');
}).listen(8085);
Node.js
Asynchronous programming techniques
Front-end web programming in which interface events (such as mouse clicks) trigger logic, then asynchronous
programming is carried out.
Server-side asynchronous programming is no different: events occur that trigger response logic.
There are two popular models in the Node world for managing response logic: callbacks and event listeners.
Callbacks generally define logic for one-off responses.
If you perform a database query, for example, you can specify a callback to determine what to do with the query
results.
The callback may display the database results, do a calculation based on the results, or execute another callback
using the query results as an argument.

Event listeners: are essentially callbacks that are associated with a conceptual entity (an event).
For comparison, a mouse click is an event you would handle in the browser when someone clicks the mouse.
As an example, in Node an HTTP server emits a request event when an HTTP request is made. You can listen for
that request event to occur and add some response logic

A Node HTTP server instance is an example of an event emitter, a class (EventEmitter) that can be inherited and
that adds the ability to emit and handle events.
Many aspects of Node’s core functionality inherit from EventEmitter, and you can also create your own.
Asynchronous programming techniques
Handling one-off events with callbacks
A callback is a function, passed as an argument to an asynchronous function, that describes what to do after the
asynchronous operation has completed.
Callbacks are used frequently in Node development, more so than event emitters, and they’re simple to use.

Handling repeating events with event emitters


Event emitters fire events and include the ability to handle those events when triggered.
Some important Node API components, such as HTTP servers, TCP servers, and streams, are implemented as
event emitters. You can also create your own.
Events are handled through the use of listeners.
A listener is the association of an event with a callback function that gets triggered each time the event occurs.

Events and Callbacks look similar but the differences lies in the fact that callback functions are called when an
asynchronous function returns its result where as event handling works on the observer pattern.
Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available
through events module and EventEmitter class which is used to bind events and event listeners.
Sequencing asynchronous logic
• During the execution of an asynchronous program, there are some tasks that can happen any time,
independent of what the rest of the program is doing, without causing problems.
• But there are also some tasks, however, that should happen only before or after certain other tasks.
• The concept of sequencing groups of asynchronous tasks is called flow control by the Node community. There
are Two types of flow control:
• Serial-Tasks that need to happen one after the other eg., A simple example would be the tasks of creating a
directory and then storing a file in it. You wouldn’t be able to store the file before creating the director
• Parallel-It isn’t necessarily important when these tasks start and stop relative to one another, but they should
all be completed before further logic executes. Eg., downloading a number of files that will later be
compressed into a zip archive. The files can be downloaded simultaneously, but all of the downloads should be
completed before creating the archive.
• Keeping track of serial and parallel flow control involves programmatic bookkeeping.
• When you implement serial flow control, you need to keep track of the task currently executing or maintain a
queue of unexecuted tasks.
• When you implement parallel flow control, you need to keep track of how many tasks have executed to
completion.
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.
Blocking Code
The program blocks until it reads the file and then only it proceeds to end the program.
Thus, a blocking program executes very much in sequence. From the programming point of view, it is easier to
implement the logic var fs = require("fs");
var http=require("http"); var data = fs.readFileSync('input.txt');
var dt= require('fs'); console.log(data.toString());
//create server console.log("Program Ended");
http.createServer(function(request,response){
var data= dt.readFileSync('input.txt');
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write(data);
response.end();
}).listen(8085);
Callback
Non-Blocking Code
non-blocking programs do not execute in sequence.
program does not wait for file reading but it just proceeded to print "Program Ended" and same time program
without blocking continues reading the file.
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
if (err) {
console.log(err.stack);
return;
}
console.log(data.toString());
});
console.log("Program Ended");
Event-Driven Programming
Node.js is a single-threaded application, but it can support concurrency via the concept of event and callbacks.
Every API of Node.js is asynchronous and being single-threaded, they use async function calls to maintain
concurrency.
Node uses observer pattern. Node thread keeps an event loop and whenever a task gets completed, it fires the
corresponding event which signals the event-listener function to execute.
Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other similar
technologies.
As soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for the
event to occur.
In an event-driven application, there is generally a main loop that listens for events, and then triggers a callback
function when one of those events is detected.
Event-Driven Programming // Import events module
// Import events module
var events = require('events');
var events = require('events');
// Create an eventEmitter object // Create an eventEmitter object
var eventEmitter = new events.EventEmitter(); var eventEmitter = new events.EventEmitter();
// Create an event handler as follows
var connectHandler = function connected() { // Bind event and event handler as follows
console.log('connection succesful.'); eventEmitter.on('eventName', eventHandler);
// Fire the data_received event
eventEmitter.emit('data_received'); // Fire an event
eventEmitter.emit('eventName');
}
// Bind the connection event with the handler
eventEmitter.on('connection', connectHandler);
// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function() {
console.log('data received succesfully.');
});
// Fire the connection event
eventEmitter.emit('connection');
console.log("Program Ended.");
Event-Driven Programming
EventEmitter class lies in the events module. It is accessible via the following code −
// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
When an EventEmitter instance faces any error, it emits an 'error' event. When a new listener is added,
'newListener' event is fired and when a listener is removed, 'removeListener' event is fired.

EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the event
and emit is used to fire an event.

addListener(event, listener)-Adds a listener at the end of the listeners array for the specified event.
once(event, listener)-Adds a one time listener to the event.
removeListener(event, listener)-Removes a listener from the listener array for the specified event.
setMaxListeners(n)-By default, EventEmitters will print a warning if more than 10 listeners are added for a
particular event.
emit(event, [arg1], [arg2], [...])-Execute each of the listeners in order with the supplied arguments. Returns true
if the event had listeners, false otherwise.
listenerCount(emitter, event)-Returns the number of listeners for a given event.
Event-Driven Programming
var events = require('events'); // Remove the binding of listner1 function
var eventEmitter = new events.EventEmitter(); eventEmitter.removeListener('connection',
// listener #1 listner1);
console.log("Listner1 will not listen now.");
var listner1 = function listner1() {
// Fire the connection event
console.log('listner1 executed.'); eventEmitter.emit('connection');
} eventListeners =
// listener #2 require('events').EventEmitter.listenerCount
var listner2 = function listner2() { (eventEmitter,'connection');
console.log('listner2 executed.'); console.log(eventListeners + " Listner(s)
} listening to connection event");
// Bind the connection event with the listner1 function console.log("Program Ended.");
eventEmitter.addListener('connection', listner1);
// Bind the connection event with the listner2 function
eventEmitter.on('connection', listner2);
var eventListeners = require('events').EventEmitter.listenerCount
(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");
// Fire the connection event
eventEmitter.emit('connection');
Module in Node.js
A set of functions you want to include in your application. Consider Modules to be the same as JavaScript
libraries.
Node.js has a set of built-in modules which can be used without any further installation.
own modules can be created, and easily include them in your applications.
Use the exports keyword to make properties and methods available outside the module file.
we use ./ to locate the module, that means that the module is located in the same folder as the Node.js file.
//egmodule.js
exports.myDateTime = function () {
return Date();
};
//firsteg.js
var http=require("http");
var dt= require('./egmodule');
//create server
http.createServer(function(request,response){
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write("Date and time "+dt.myDateTime());
response.end();
}).listen(8085);
Node.js File System Module
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');
Read FilesThe fs.readFile() method is used to read files on your computer.
Create Files
The File System module has methods for creating new files:
fs.appendFile()-The fs.appendFile() method appends specified content to a file. If the file does not exist, the file
will be created
fs.open()-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
fs.writeFile()-method replaces the specified file and content if it exists. If the file does not exist, a new file,
containing the specified content, will be created
Update Files
The File System module has methods for updating files:
fs.appendFile()-method appends the specified content at the end of the specified file
fs.writeFile()-method replaces the specified file and content
Delete Files
To delete a file with the File System module, use the fs.unlink() method
Rename Files
To rename a file with the File System module, use the fs.rename() method
Node.js File System Module
var http=require("http");
var dt= require('fs');
//create server
http.createServer(function(request,response){
dt.readFile('demo.html', function(err, data) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write(data);
return response.end();
});
}).listen(8085);
Node.js –Global Objects
Node.js global objects are global in nature and they are available in all modules. We do not need to include these
objects in our application, rather we can use them directly.
__filenameThe __filename represents the filename of the code being executed.
__dirnameThe __dirname represents the name of the directory that the currently executing script resides in.
setTimeout(cb, ms)The setTimeout(cb, ms) global function is used to run callback cb after at least ms
milliseconds.
clearTimeout(t)The clearTimeout(t) global function is used to stop a timer that was previously created with
setTimeout().
setInterval(cb, ms)The setInterval(cb, ms) global function is used to run callback cb repeatedly after at least ms
milliseconds.
console.log( __filename );
console.log( __dirname );
function printHello() {
console.log( "Hello, World!");
}
// Now call above function after 2 seconds
setTimeout(printHello, 2000);

function printHello() {
console.log( "Hello, World!");
}
// Now call above function after 2 seconds
setInterval(printHello, 2000);
Node.js –Global Objects
ProcessUsed to get information on current process. Provides multiple events related to process activities.
Console is a global object and is used to print different levels of messages to stdout and stderr. There are built-in
methods to be used for printing informational, warning, and error messages.
Process Events
exitEmitted when the process is about to exit.
beforeExitThis event is emitted when node empties its event loop and has nothing else to schedule.
uncaughtExceptionEmitted when an exception bubbles all the way back to the event loop.

process.stdout.write("Hello World!" + "\n");


// Reading passed parameter
process.argv.forEach(function(val, index, array) {
console.log(index + ': ' + val);
});
// Getting executable path
console.log(process.execPath);
// Platform Information
console.log(process.platform);
Node.js –Global Objects
process.on('exit', function(code) {
// Following code will never execute.
setTimeout(function() {
console.log("This will not run");
}, 0);
console.log('About to exit with code:', code);
});
console.log("Program Ended");

console.log('Current directory: ' + process.cwd());


// Print the process version
console.log('Current version: ' + process.version);
// Print the memory usage
console.log(process.memoryUsage());

You might also like