SlideShare a Scribd company logo
What is Full Stack Web Development?
by
Krishnapriya
Few Terms and Terminologies
Node.js
Node.js
Node.js
Node.js
Introduction
• Node.js is a JavaScript runtime built on
Chrome's V8 JavaScript engine. Node.js
uses an event-driven, non-blocking I/O
model that makes it lightweight and
efficient.
• Node.js was developed by Ryan Dahl in
2009 and its latest version is v7.0.0.
Node.js architecture
Features of Node.js
• Powerful js framework which works on cross
platform
• Asynchronous and Event Driven
All APIs of Node.js library are asynchronous, that is, non-blocking.
• Very Fast
Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very
fast in code execution.
• Single Threaded but Highly Scalable
Node.js uses a single threaded model with event looping
• No Buffering
Node.js applications never buffer any data. These applications simply output
the data in chunks.
• Node.js is released under the MIT license
When to use
• When making system which put emphasis on concurrency and speed.
• Sockets only servers like chat apps, irc apps, etc.
• Social networks which put emphasis on realtime resources like
geolocation, video stream, audio stream, etc.
• Handling small chunks of data really fast like an analytics webapp.
Where Not to Use Node.js?
It is not advisable to use Node.js for CPU intensive applications.
http://www.algoworks.com/blog/developing-enterprise-applications-using-
node-js/
Following are the sample applications
for which node.js is much suitable:
• I/O based Applications
• Data Streaming Applications
• Data Intensive Real-time
Applications (DIRT)
• JSON APIs based Applications
• Single Page Applications
V8 --->Javascript Engine
• It is a open source javascript engine written in C++.
• It is used in client side in Chrome browser and server side in NodeJs.
• V8 can run standalone and can be embedded into any C++ application.
• Its was designed to increase performance of Javascript execution inside web
browsers.
• V8 translates JavaScript code into more efficient machine code instead of
using an interpreter and does not produce byte code or any intermediate
code.
• To Check Version of V8 installed:
• Type in terminal :
• node -p process.versions.v8
NodeJS Installation
• Installing On Linux:
sudo apt-get update
sudo apt-get install nodejs
sudo apt-get install npm
• Just close the terminal and reopen it and type:
node –v
• Install on Windows:
Download the MSI for Node and install it and follow the
instructions.
Open The CMD and type node -v, it should say version of
nodejs.
NodeJS REPL Mode
REPL stands for Read Eval Print Loop and it represents a computer
environment like a Windows console or Unix/Linux shell where a command is
entered and the system responds with an output in an interactive mode.
• There are a few REPL-specific commands available to you, which can be
displayed by typing: .help
> 3+1
4
> x=3
3
> var x=3
undefined
> console.log('Hello World')
Hello World
undefined
> var http= require('http')
undefined
REPL Commands
• ctrl + c − terminate the current command.
• ctrl + c twice − terminate the Node REPL.
• ctrl + d − terminate the Node REPL.
• Up/Down Keys − see command history and
modify previous commands.
• tab Keys − list of current commands.
• .help − list of all commands.
• .save filename − save the current Node REPL
session to a file.
Node JS REPL mode….
• We can change default prompt(>) to custom :
node -e "require('repl').start({prompt : 'username>>'})"
• We can ignore Undefined returned REPL in node in case
of statement which return nothing like, var x=9; As
javascript returns something if nothing is returned it
returns Undefined as value. To ignore it we can type:
node -e "require('repl').start({prompt :
'username>>>',ignoreUndefined : true})"
• Run example code repl_output.js to see case change of
output in console.
Add New Commands to REPL
• Type .help to see available default
commands in REPL mode.
• Demo code to add new command:
replcommand1.js
replcommand2.js
Type to run:
node replcommand1.js
.help (to see command
added in list)
Creating a simple server with
node Environment
A Node.js application consists of the following three important components −
1) Import required modules − We use the require directive to load Node.js
modules.
2) Create server − A server which will listen to client's requests similar to
Apache HTTP Server.
3) Read request and return response − The server created in an earlier
step will read the HTTP request made by the client which can be a browser or
a console and return the response.
Demo Example: helloworld.js
Node Package Manager (NPM)
Node Package Manager (NPM) provides two
main functionalities −
• Online repositories for node.js
packages/modules which are searchable
on search.nodejs.org
• Command line utility to install Node.js
packages, do version management and
dependency management of Node.js packages.
NodeJS and NPM
• It is automatically installed with Node.js, and we use NPM to
install new modules.
• It is a Node module that is installed globally with the initial
installation of Node. By default, it searches and loads
packages from the npm registry.
• To install a module, open your terminal/command line,
navigate to the desired folder, and execute the following
command:
npm install module_name
Simply executing npm install will install all the modules listed in
the package.json file in local local node_modules folder in the
current directory.
• npm install <name> tries to install the most recent version of
the module <name> into the local node_modules folder.
NodejS and NPM …..
//To check npm version
npm –version
//To check all modules installed in current directory
npm ls
//To check modules installed globally
npm ls –g
//To uninstall a module
npm uninstall <module_name>
//To uninstall a update
npm update <module_name>
//To search a module
npm search <module_name>
//To Interactively create a package.json
npm init
//To automate publishing of npm modules
npm publish
NPM and Package.Json
NPM and Package.json ….
• name: is the name of the module. This is required, but only needs to
be unique if you plan on publishing the module to the npm registry.
• version: is the version of the package expressed as
major.minor.patch. This is known as semantic versioning, and it is
recommended to start with version 1.0.0.
• scripts: This key serves a unique purpose, providing additional npm
commands when running from this directory.
• dependencies: This is generally where the majority of information in
any package.json file is stored. dependencies lists all the modules
that the current module or application needs to function.
• Run npm init in the terminal and it will guide you through a series of
prompts. This will generate a simple package.json file that’s in line
with the community standard and the latest specification from npm.
• When there is a package.json file , running npm install
module_name will install that module and update dependencies in
package.json file to include an entry for those module.
NPM require() function
• The require function is specific to Node and is unavailable to
web browsers. require('http') will cause Node to try to locate a
module named http. The lookup procedure roughly works in
this way:
1. Check to see if the module named is a core module.
2. Check in the current directory’s node_modules folder.
3. Move up one directory and look inside the node_modules
folder if present.
4. Repeat until the root directory is reached.
5. Check in the global directory.
6. Throw an error because the module could not be found.
Modules
• Node.js uses a module architecture to simplify
the creation of complex applications. Modules
are akin to libraries in C.
• Then there are modules available for social
authentication, validation, and even server
frameworks such as ExpressJS and Hapi.
• Each module contains a set of functions related
to the "subject" of the module.
• For example, the http module contains
functions specific to HTTP.
Modules ……
• Including a module is easy, simply call the
require() function, like this:
var http = require('http');
• The require() function returns the
reference to the specified module.
• This causes Node to search for a
node_modules folder in our application's
directory, and search for the http module
in that folder. If Node does not find the
node_modules folder (or the http module
within it), it then looks through the global
module cache.
WritingModule locally
1) Create folder mmm Write a file save it as
mmm.js
2) Go to mmm folder and Run npm init ,
it will prompt you for values for the package.json fields. The two
required fields are name and version.
3) Go to mmm folder and Run npm pack
This pack command creates mmm-1.0.0.tgz file (this is your node
packaged module locally )
4) To install it , just go to any folder and run
npm install (path to mmm-1.0.0.tgz file)
ex: >npm install ..modmmm-1.0.0.tgz
5) To test the newly installed module create test.js and run it.
Writing Module Globally
1) Create a folder
2) Go to folder and run : npm init
name is mandatory should keep unique and press enter to set default
values.
3) Create a new git repository and upload files there, by default
README.md file will create in GIT.
4) Now edit package.json file in git repository as well as in folder you
have made and add the
"repository": {
"type": "git",
"url": "https://github.com/kpriyacdac/kpriyamodule"
},
5) Run in same folder you made : npm adduser
*** npm install looks for package.json file and install alll dependencies . If not found
package.json file it gives a warning but makes a empty node_modules folder
npm install <module_name> willl install this module and after that will lokk for
package.json file to install or update other dependencies if any mentioned.
Event Loop
• 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.
• JavaScript engine maintains several queues of unhandled tasks. These
queues include things such as events, timers, intervals. Each execution of
the event loop, known as a cycle, causes one or more tasks to be de-
queued and executed. Demo example file: eventloop.js
• Nodejs almost exclusively uses asynchronous non-blocking I/O. Under this
paradigm, an application will initiate some long-running external operation
such as I/O, however, instead of waiting for a response, the program will
continue executing additional code. Once the asynchronous operation is
finished, the results are passed back to the Node application for processing.
Few ways it can be done:
The two most popular ways in Node are:
1. callback functions (more priority)
2. event emitters
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..
Conventions followed:
1. When passing a callback function as an argument, it should be the last
argument.
2. error is the first argument to the callback function.
Demo example syncnode.js to see synchronous nature.
Demo example asyncnode.js to see asynchronous nature and callback.
Event Emitters
• The second way to implement asynchronous
code is via events. Under this model, objects
called event emitters create or publish events.
For example, in the browser, an event could be a
mouse click or key press.
Demo example of event :
event .js
Node.js - Buffers
• Node provides Buffer class which provides
instances to store raw data similar to an array of
integers but corresponds to a raw memory
allocation outside the V8 heap.
• Buffer class is a global class that can be
accessed in an application without importing the
buffer module.
Example:
buf = new Buffer(256);
len = buf.write("Simply Easy Learning");
console.log("Octets written : "+ len);
Working with the File System
The fs module allows you to access the file system.
• __filename and __dirname are strings, and, as their names imply,
they specify the file being executed and the directory containing the
file. They are local variables that are defined in every file.
Demo code: file_path.js
Reading Files:
• fs module’s readFile() and readFileSync() methods. Both of these
methods take a filename to read as their first argument. An optional
second argument can be used to specify additional options such as
the character encoding . I f the encoding is not specified, the
contents of the file are returned in a Buffer (a Node data type used to
store raw binary data). Example code: readfile.js
• There are two ways to view the data as a string:
1. First is to call toString() on the data variable. This will return the
Buffer contents as a UTF-8 encoded string.
2. The another way to specify UTF-8 encoding using the optional
second argument.
Example file: file.js.
Working with the File System…..
• Compare codes file.js and file1.js to see difference between
readFile and readFileSync methods
• To get a file info run the program: info.js
Writing Files:
• Files can easily be written using the writeFile() and writeFileSync()
methods. These methods are the counterparts of readFile() and
readFileSync().
• These methods take a filename as their first argument, and the data
to write (as a string or Buffer) as their second argument. The third
argument is optional, and is used to pass additional information such
as the encoding type.
• Unlike the readFile() variations, these methods default to using
UTF-8 encoding. writeFile() takes a callback function as its last
argument.
• Example code run: writefile.js
Debugging
• Debugging, as the name suggests, is the process of tracking down
bugs and fixing them. The process of debugging can be as simple
as adding console.log() calls to your code to verify that certain
variables hold expected values.
• All major JavaScript environments (browsers, Nodejs, and so on)
come with a built-in debugger. However, the debugger is not
typically enabled by default.
• JavaScript’s debugger statement is used to invoke a debugger on
an application, if one is attached. If an application has no debugger
associated with it, the debugger statement has no effect.
• Open Chrome’s developer tools by right-clicking on the page and
clicking Inspect Element. Next, refresh the page. Doing this with the
developer tools enabled allows the debugger to be attached.
Debugging With Chrome
• Demo Code : debug.html
• Open Chrome’s developer tools by right-clicking on the page and
clicking Inspect Element. Next, refresh the page. Doing this with the
developer tools enabled allows the debugger to be attached. The
execution pauses at debugger statement.
• This predefined pause in execution is known as a breakpoint.
• On the right-hand side of the image, notice the two panels, Scope
Variables and Global. These panels can be expanded to view the
variables and values in the local and global scope respectively.
• Our code is currently executing in the global scope, so nothing is
listed in the Scope Variables panel. Expand the Global panel and
scroll down until you find i and j.
• In right panel there are controls to resume execution step in ,
deactivate breakpoint. We can edit value of vriables. The value
edited persist even out of debugger.
•
•
•
Node Debugging
• Node ships with a built-in debugger. To debug a file just type as
below: node debug filename
The following table specify commands for debugging:

More Related Content

What's hot (20)

PPTX
Introduction to Node.js
AMD Developer Central
 
PPTX
HTTP Request Header and HTTP Status Code
Abhishek L.R
 
PDF
Express node js
Yashprit Singh
 
PDF
ES2015 / ES6: Basics of modern Javascript
Wojciech Dzikowski
 
PPTX
ReactJS presentation.pptx
DivyanshGupta922023
 
PDF
Angular Advanced Routing
Laurent Duveau
 
PPTX
Angular tutorial
Rohit Gupta
 
PPTX
Basic Concept of Node.js & NPM
Bhargav Anadkat
 
PPTX
Reactjs
Neha Sharma
 
PDF
NodeJS for Beginner
Apaichon Punopas
 
PPTX
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
PPTX
Introduction to Spring Framework
Serhat Can
 
PPTX
Laravel ppt
Mayank Panchal
 
PPT
Node.js Basics
TheCreativedev Blog
 
PPTX
React js
Oswald Campesato
 
PPTX
Introduction to Node.js
Vikash Singh
 
PPTX
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Malla Reddy University
 
PPT
React js
Jai Santhosh
 
PPTX
Introduction to node.js
Dinesh U
 
Introduction to Node.js
AMD Developer Central
 
HTTP Request Header and HTTP Status Code
Abhishek L.R
 
Express node js
Yashprit Singh
 
ES2015 / ES6: Basics of modern Javascript
Wojciech Dzikowski
 
ReactJS presentation.pptx
DivyanshGupta922023
 
Angular Advanced Routing
Laurent Duveau
 
Angular tutorial
Rohit Gupta
 
Basic Concept of Node.js & NPM
Bhargav Anadkat
 
Reactjs
Neha Sharma
 
NodeJS for Beginner
Apaichon Punopas
 
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
Introduction to Spring Framework
Serhat Can
 
Laravel ppt
Mayank Panchal
 
Node.js Basics
TheCreativedev Blog
 
Introduction to Node.js
Vikash Singh
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Malla Reddy University
 
React js
Jai Santhosh
 
Introduction to node.js
Dinesh U
 

Viewers also liked (15)

PPT
Presentacion poa 2011
NATHALY ARIAS
 
PPTX
Mi futuro como maestra
minerva0404
 
DOC
Rpp kd 1.1
Ahmad Saripudin
 
PDF
RESPONSABILIDAD SOCIAL EMPRESARIAL
NATHALY ARIAS
 
DOC
Updated resume
Jayendra Rathor
 
PPTX
Formar identidad
minerva0404
 
PPT
Liderazgo y administracion de calidad Ediluz Fuenmayor
Efuenmayorb
 
PPS
Los modelos administrativos en el contexto de la sociedad post moderna
NATHALY ARIAS
 
PPS
Modelos administrativos
NATHALY ARIAS
 
PPTX
Noticias inmobiliarias de hoy - 7 de noviembre
Prueba Social
 
PPTX
Gallucci_Garcia_presentacionfinal
IrianaGarcia
 
PPTX
Act 3 writing task forum
Ancel Medina
 
PPTX
Componentes ordenador
Moni Pérez Beltrán
 
PDF
LADY_ARIAS_PRESENTACION
NATHALY ARIAS
 
PDF
Japón
ipiquera
 
Presentacion poa 2011
NATHALY ARIAS
 
Mi futuro como maestra
minerva0404
 
Rpp kd 1.1
Ahmad Saripudin
 
RESPONSABILIDAD SOCIAL EMPRESARIAL
NATHALY ARIAS
 
Updated resume
Jayendra Rathor
 
Formar identidad
minerva0404
 
Liderazgo y administracion de calidad Ediluz Fuenmayor
Efuenmayorb
 
Los modelos administrativos en el contexto de la sociedad post moderna
NATHALY ARIAS
 
Modelos administrativos
NATHALY ARIAS
 
Noticias inmobiliarias de hoy - 7 de noviembre
Prueba Social
 
Gallucci_Garcia_presentacionfinal
IrianaGarcia
 
Act 3 writing task forum
Ancel Medina
 
Componentes ordenador
Moni Pérez Beltrán
 
LADY_ARIAS_PRESENTACION
NATHALY ARIAS
 
Japón
ipiquera
 
Ad

Similar to Node.js (20)

PPTX
Overview of Node JS
Jacob Nelson
 
PPTX
Introduction to NodeJS JSX is an extended Javascript based language used by R...
JEEVANANTHAMG6
 
DOCX
unit 2 of Full stack web development subject
JeneferAlan1
 
PPTX
Mastering node.js, part 1 - introduction
cNguyn826690
 
PPTX
Basics of Node.js
Alper Unal
 
PPTX
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
PPTX
Intro to Node.js (v1)
Chris Cowan
 
PPTX
A complete guide to Node.js
Prabin Silwal
 
PDF
Node js
Rohan Chandane
 
PDF
Nodejs vatsal shah
Vatsal N Shah
 
PDF
Node JS - A brief overview on building real-time web applications
Expeed Software
 
PDF
Introduction to Node js for beginners + game project
Laurence Svekis ✔
 
PPTX
Node js meetup
Ansuman Roy
 
PDF
🚀 Node.js Simplified – A Visual Guide for Beginners!
Tpoint Tech Blog
 
PPTX
Node js Powerpoint Presentation by PDEU Gandhinagar
tirthuce22
 
PPTX
Introduction to node.js By Ahmed Assaf
Ahmed Assaf
 
PDF
Server Side Apocalypse, JS
Md. Sohel Rana
 
PPTX
node_js.pptx
dipen55
 
PPTX
node.js.pptx
rani marri
 
PPTX
Intro To Node.js
Chris Cowan
 
Overview of Node JS
Jacob Nelson
 
Introduction to NodeJS JSX is an extended Javascript based language used by R...
JEEVANANTHAMG6
 
unit 2 of Full stack web development subject
JeneferAlan1
 
Mastering node.js, part 1 - introduction
cNguyn826690
 
Basics of Node.js
Alper Unal
 
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
Intro to Node.js (v1)
Chris Cowan
 
A complete guide to Node.js
Prabin Silwal
 
Nodejs vatsal shah
Vatsal N Shah
 
Node JS - A brief overview on building real-time web applications
Expeed Software
 
Introduction to Node js for beginners + game project
Laurence Svekis ✔
 
Node js meetup
Ansuman Roy
 
🚀 Node.js Simplified – A Visual Guide for Beginners!
Tpoint Tech Blog
 
Node js Powerpoint Presentation by PDEU Gandhinagar
tirthuce22
 
Introduction to node.js By Ahmed Assaf
Ahmed Assaf
 
Server Side Apocalypse, JS
Md. Sohel Rana
 
node_js.pptx
dipen55
 
node.js.pptx
rani marri
 
Intro To Node.js
Chris Cowan
 
Ad

More from krishnapriya Tadepalli (14)

PDF
Web content accessibility
krishnapriya Tadepalli
 
PPTX
Data visualization tools
krishnapriya Tadepalli
 
PDF
Drupal vs sitecore comparisons
krishnapriya Tadepalli
 
PPT
Open Source Content Management Systems
krishnapriya Tadepalli
 
PDF
My sql vs mongo
krishnapriya Tadepalli
 
PDF
Comparisons Wiki vs CMS
krishnapriya Tadepalli
 
PDF
Sending emails through PHP
krishnapriya Tadepalli
 
PDF
PHP Making Web Forms
krishnapriya Tadepalli
 
PDF
Php introduction
krishnapriya Tadepalli
 
PDF
Using advanced features in joomla
krishnapriya Tadepalli
 
PDF
Presentation joomla-introduction
krishnapriya Tadepalli
 
PDF
Making web forms using php
krishnapriya Tadepalli
 
PDF
Language enabling
krishnapriya Tadepalli
 
Web content accessibility
krishnapriya Tadepalli
 
Data visualization tools
krishnapriya Tadepalli
 
Drupal vs sitecore comparisons
krishnapriya Tadepalli
 
Open Source Content Management Systems
krishnapriya Tadepalli
 
My sql vs mongo
krishnapriya Tadepalli
 
Comparisons Wiki vs CMS
krishnapriya Tadepalli
 
Sending emails through PHP
krishnapriya Tadepalli
 
PHP Making Web Forms
krishnapriya Tadepalli
 
Php introduction
krishnapriya Tadepalli
 
Using advanced features in joomla
krishnapriya Tadepalli
 
Presentation joomla-introduction
krishnapriya Tadepalli
 
Making web forms using php
krishnapriya Tadepalli
 
Language enabling
krishnapriya Tadepalli
 

Recently uploaded (20)

PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
THE TAME BIRD AND THE FREE BIRD.pptxxxxx
MarcChristianNicolas
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PPTX
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PPTX
BANDHA (BANDAGES) PPT.pptx ayurveda shalya tantra
rakhan78619
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PPSX
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
THE TAME BIRD AND THE FREE BIRD.pptxxxxx
MarcChristianNicolas
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
community health nursing question paper 2.pdf
Prince kumar
 
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
BANDHA (BANDAGES) PPT.pptx ayurveda shalya tantra
rakhan78619
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 

Node.js

  • 1. What is Full Stack Web Development? by Krishnapriya
  • 2. Few Terms and Terminologies
  • 7. Introduction • Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. • Node.js was developed by Ryan Dahl in 2009 and its latest version is v7.0.0.
  • 9. Features of Node.js • Powerful js framework which works on cross platform • Asynchronous and Event Driven All APIs of Node.js library are asynchronous, that is, non-blocking. • Very Fast Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution. • Single Threaded but Highly Scalable Node.js uses a single threaded model with event looping • No Buffering Node.js applications never buffer any data. These applications simply output the data in chunks. • Node.js is released under the MIT license
  • 10. When to use • When making system which put emphasis on concurrency and speed. • Sockets only servers like chat apps, irc apps, etc. • Social networks which put emphasis on realtime resources like geolocation, video stream, audio stream, etc. • Handling small chunks of data really fast like an analytics webapp. Where Not to Use Node.js? It is not advisable to use Node.js for CPU intensive applications. http://www.algoworks.com/blog/developing-enterprise-applications-using- node-js/
  • 11. Following are the sample applications for which node.js is much suitable: • I/O based Applications • Data Streaming Applications • Data Intensive Real-time Applications (DIRT) • JSON APIs based Applications • Single Page Applications
  • 12. V8 --->Javascript Engine • It is a open source javascript engine written in C++. • It is used in client side in Chrome browser and server side in NodeJs. • V8 can run standalone and can be embedded into any C++ application. • Its was designed to increase performance of Javascript execution inside web browsers. • V8 translates JavaScript code into more efficient machine code instead of using an interpreter and does not produce byte code or any intermediate code. • To Check Version of V8 installed: • Type in terminal : • node -p process.versions.v8
  • 13. NodeJS Installation • Installing On Linux: sudo apt-get update sudo apt-get install nodejs sudo apt-get install npm • Just close the terminal and reopen it and type: node –v • Install on Windows: Download the MSI for Node and install it and follow the instructions. Open The CMD and type node -v, it should say version of nodejs.
  • 14. NodeJS REPL Mode REPL stands for Read Eval Print Loop and it represents a computer environment like a Windows console or Unix/Linux shell where a command is entered and the system responds with an output in an interactive mode. • There are a few REPL-specific commands available to you, which can be displayed by typing: .help > 3+1 4 > x=3 3 > var x=3 undefined > console.log('Hello World') Hello World undefined > var http= require('http') undefined
  • 15. REPL Commands • ctrl + c − terminate the current command. • ctrl + c twice − terminate the Node REPL. • ctrl + d − terminate the Node REPL. • Up/Down Keys − see command history and modify previous commands. • tab Keys − list of current commands. • .help − list of all commands. • .save filename − save the current Node REPL session to a file.
  • 16. Node JS REPL mode…. • We can change default prompt(>) to custom : node -e "require('repl').start({prompt : 'username>>'})" • We can ignore Undefined returned REPL in node in case of statement which return nothing like, var x=9; As javascript returns something if nothing is returned it returns Undefined as value. To ignore it we can type: node -e "require('repl').start({prompt : 'username>>>',ignoreUndefined : true})" • Run example code repl_output.js to see case change of output in console.
  • 17. Add New Commands to REPL • Type .help to see available default commands in REPL mode. • Demo code to add new command: replcommand1.js replcommand2.js Type to run: node replcommand1.js .help (to see command added in list)
  • 18. Creating a simple server with node Environment A Node.js application consists of the following three important components − 1) Import required modules − We use the require directive to load Node.js modules. 2) Create server − A server which will listen to client's requests similar to Apache HTTP Server. 3) Read request and return response − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response. Demo Example: helloworld.js
  • 19. Node Package Manager (NPM) Node Package Manager (NPM) provides two main functionalities − • Online repositories for node.js packages/modules which are searchable on search.nodejs.org • Command line utility to install Node.js packages, do version management and dependency management of Node.js packages.
  • 20. NodeJS and NPM • It is automatically installed with Node.js, and we use NPM to install new modules. • It is a Node module that is installed globally with the initial installation of Node. By default, it searches and loads packages from the npm registry. • To install a module, open your terminal/command line, navigate to the desired folder, and execute the following command: npm install module_name Simply executing npm install will install all the modules listed in the package.json file in local local node_modules folder in the current directory. • npm install <name> tries to install the most recent version of the module <name> into the local node_modules folder.
  • 21. NodejS and NPM ….. //To check npm version npm –version //To check all modules installed in current directory npm ls //To check modules installed globally npm ls –g //To uninstall a module npm uninstall <module_name> //To uninstall a update npm update <module_name> //To search a module npm search <module_name> //To Interactively create a package.json npm init //To automate publishing of npm modules npm publish
  • 23. NPM and Package.json …. • name: is the name of the module. This is required, but only needs to be unique if you plan on publishing the module to the npm registry. • version: is the version of the package expressed as major.minor.patch. This is known as semantic versioning, and it is recommended to start with version 1.0.0. • scripts: This key serves a unique purpose, providing additional npm commands when running from this directory. • dependencies: This is generally where the majority of information in any package.json file is stored. dependencies lists all the modules that the current module or application needs to function. • Run npm init in the terminal and it will guide you through a series of prompts. This will generate a simple package.json file that’s in line with the community standard and the latest specification from npm. • When there is a package.json file , running npm install module_name will install that module and update dependencies in package.json file to include an entry for those module.
  • 24. NPM require() function • The require function is specific to Node and is unavailable to web browsers. require('http') will cause Node to try to locate a module named http. The lookup procedure roughly works in this way: 1. Check to see if the module named is a core module. 2. Check in the current directory’s node_modules folder. 3. Move up one directory and look inside the node_modules folder if present. 4. Repeat until the root directory is reached. 5. Check in the global directory. 6. Throw an error because the module could not be found.
  • 25. Modules • Node.js uses a module architecture to simplify the creation of complex applications. Modules are akin to libraries in C. • Then there are modules available for social authentication, validation, and even server frameworks such as ExpressJS and Hapi. • Each module contains a set of functions related to the "subject" of the module. • For example, the http module contains functions specific to HTTP.
  • 26. Modules …… • Including a module is easy, simply call the require() function, like this: var http = require('http'); • The require() function returns the reference to the specified module. • This causes Node to search for a node_modules folder in our application's directory, and search for the http module in that folder. If Node does not find the node_modules folder (or the http module within it), it then looks through the global module cache.
  • 27. WritingModule locally 1) Create folder mmm Write a file save it as mmm.js 2) Go to mmm folder and Run npm init , it will prompt you for values for the package.json fields. The two required fields are name and version. 3) Go to mmm folder and Run npm pack This pack command creates mmm-1.0.0.tgz file (this is your node packaged module locally ) 4) To install it , just go to any folder and run npm install (path to mmm-1.0.0.tgz file) ex: >npm install ..modmmm-1.0.0.tgz 5) To test the newly installed module create test.js and run it.
  • 28. Writing Module Globally 1) Create a folder 2) Go to folder and run : npm init name is mandatory should keep unique and press enter to set default values. 3) Create a new git repository and upload files there, by default README.md file will create in GIT. 4) Now edit package.json file in git repository as well as in folder you have made and add the "repository": { "type": "git", "url": "https://github.com/kpriyacdac/kpriyamodule" }, 5) Run in same folder you made : npm adduser *** npm install looks for package.json file and install alll dependencies . If not found package.json file it gives a warning but makes a empty node_modules folder npm install <module_name> willl install this module and after that will lokk for package.json file to install or update other dependencies if any mentioned.
  • 29. Event Loop • 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. • JavaScript engine maintains several queues of unhandled tasks. These queues include things such as events, timers, intervals. Each execution of the event loop, known as a cycle, causes one or more tasks to be de- queued and executed. Demo example file: eventloop.js • Nodejs almost exclusively uses asynchronous non-blocking I/O. Under this paradigm, an application will initiate some long-running external operation such as I/O, however, instead of waiting for a response, the program will continue executing additional code. Once the asynchronous operation is finished, the results are passed back to the Node application for processing. Few ways it can be done: The two most popular ways in Node are: 1. callback functions (more priority) 2. event emitters
  • 30. 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.. Conventions followed: 1. When passing a callback function as an argument, it should be the last argument. 2. error is the first argument to the callback function. Demo example syncnode.js to see synchronous nature. Demo example asyncnode.js to see asynchronous nature and callback.
  • 31. Event Emitters • The second way to implement asynchronous code is via events. Under this model, objects called event emitters create or publish events. For example, in the browser, an event could be a mouse click or key press. Demo example of event : event .js
  • 32. Node.js - Buffers • Node provides Buffer class which provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. • Buffer class is a global class that can be accessed in an application without importing the buffer module. Example: buf = new Buffer(256); len = buf.write("Simply Easy Learning"); console.log("Octets written : "+ len);
  • 33. Working with the File System The fs module allows you to access the file system. • __filename and __dirname are strings, and, as their names imply, they specify the file being executed and the directory containing the file. They are local variables that are defined in every file. Demo code: file_path.js Reading Files: • fs module’s readFile() and readFileSync() methods. Both of these methods take a filename to read as their first argument. An optional second argument can be used to specify additional options such as the character encoding . I f the encoding is not specified, the contents of the file are returned in a Buffer (a Node data type used to store raw binary data). Example code: readfile.js • There are two ways to view the data as a string: 1. First is to call toString() on the data variable. This will return the Buffer contents as a UTF-8 encoded string. 2. The another way to specify UTF-8 encoding using the optional second argument. Example file: file.js.
  • 34. Working with the File System….. • Compare codes file.js and file1.js to see difference between readFile and readFileSync methods • To get a file info run the program: info.js Writing Files: • Files can easily be written using the writeFile() and writeFileSync() methods. These methods are the counterparts of readFile() and readFileSync(). • These methods take a filename as their first argument, and the data to write (as a string or Buffer) as their second argument. The third argument is optional, and is used to pass additional information such as the encoding type. • Unlike the readFile() variations, these methods default to using UTF-8 encoding. writeFile() takes a callback function as its last argument. • Example code run: writefile.js
  • 35. Debugging • Debugging, as the name suggests, is the process of tracking down bugs and fixing them. The process of debugging can be as simple as adding console.log() calls to your code to verify that certain variables hold expected values. • All major JavaScript environments (browsers, Nodejs, and so on) come with a built-in debugger. However, the debugger is not typically enabled by default. • JavaScript’s debugger statement is used to invoke a debugger on an application, if one is attached. If an application has no debugger associated with it, the debugger statement has no effect. • Open Chrome’s developer tools by right-clicking on the page and clicking Inspect Element. Next, refresh the page. Doing this with the developer tools enabled allows the debugger to be attached.
  • 36. Debugging With Chrome • Demo Code : debug.html • Open Chrome’s developer tools by right-clicking on the page and clicking Inspect Element. Next, refresh the page. Doing this with the developer tools enabled allows the debugger to be attached. The execution pauses at debugger statement. • This predefined pause in execution is known as a breakpoint. • On the right-hand side of the image, notice the two panels, Scope Variables and Global. These panels can be expanded to view the variables and values in the local and global scope respectively. • Our code is currently executing in the global scope, so nothing is listed in the Scope Variables panel. Expand the Global panel and scroll down until you find i and j. • In right panel there are controls to resume execution step in , deactivate breakpoint. We can edit value of vriables. The value edited persist even out of debugger. • • •
  • 37. Node Debugging • Node ships with a built-in debugger. To debug a file just type as below: node debug filename The following table specify commands for debugging:

Editor's Notes