SlideShare a Scribd company logo
Node js
with npm,
installing express js
@RohanChandane

Last updated on 13th Oct 2013
Installing Node
nodejs.org
Hello World
...

On windows machine,
- Setting up environment variable is built in inside nodejs
directory
- after installation, type nodevars to install environment variable.
nodevars.bat is a batch file responsible for setting it up
What is Node / Node js?
- Node is Command line tool
- Download it and install
- It runs javascript code by typing ‘node your-script-file.js’

- Hosted on V8 Javascript engine
- uses V8 as standalone engine to execute javascript.

- Server-side javascript
- Node provides JavaScript API to access network & file system.
- These JavaScript files runs on the server rather than on the client side
- We can also write a server, which can be a replacement for something like
the Apache web server
...
- Uses event-driven I/O (non-blocking I/O)
- is just a term that describes the normal asynchronous callback
mechanisms.
- In node.js you supply callback functions for all sorts of things, and your
function is called when the relevant event occurs.
- So that means, it works parallelly on different I/O operations.
- eg. Code for reading from a file & reading values from a database can be
executed one after another (since node js is single threaded), and it will wait for
data to receive from file & database.
Once it receives data, it will call callback function related to function call.

- One language
- to write server side and client side code
- No need to learn server side language like Java & PHP
Why Node
1. Efficiency
- Response time
= server-side script execution time + time taken for I/O operation

- Node reduces the response time to the duration it takes to execute
the slowest I/O query
- Its mainly because ‘Single threaded - Event loop’
- Also called Event driven computing Architecture

- There is a need for high performance web servers
...
2. JavaScript
- JavaScript is universal language for web
developers
- Its single threaded
- Its dynamic

3. Speed
- Up till now, JavaScript was related to
browser
- We used it for DOM manipulation
- and our favourite browser to execute
javascript, is Chrome
...
- Chrome uses V8 engine
underneath to execute js
- V8 is the fastest javascript
execution engine
- V8 was designed to run in
Chrome’s multi-process model

V8 engine

- V8 is intended to be used both in a browser
and as a standalone high-performance engine
Asynchronous callback mechanisms
4. callbacks are invoked

functions, which are initiating
- I/O operations
- writing to a socket
- making a database query
& not going to return the value
immediately

event loop

3. event occurs

1. registers callbacks

2. loop wait for events

There's a single thread, and a single event loop, that handles all IO in node.js
Writing Server-side js with Node
Now, lets see how to write a server in
JavaScript
- creating 'server.js'
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);

- executing it:
node server.js
Passing function as parameter
lets say
function execute(someFunction, value) {
someFunction(value);
}
execute(function(word){ console.log(word) }, "Hello");

can also be written
function say(word) {
console.log(word);
}
function execute(someFunction, value) {
someFunction(value);
}
execute(say, "Hello");
Understanding server.js
var http = require("http");
function onRequest(request, response) {
console.log("Callback invoked");
response.writeHead(200, {"Content-Type":
"text/plain"});
response.write("Hello World");
response.end();
}
1
2
http.createServer(onRequest).listen(8888);
console.log("Server started");

3

4
single thread
...
This ‘server.js’ program executes in following
order
1. registers callbacks

onRequest

2. loop wait for events

listen(8888)

3. event occurs

Browser requests - localhost:8888

4. callbacks are invoked

function onRequest() gets execute
Some Basic Core Modules
Node has several modules compiled into the binary. Defined in node's
source in the lib/ folder. To load use require('modules identifier')

- HTTP

how to use require('http')

- Net

how to use require('net')

- DNS

how to use require('dns')

- Events

how to use require('events')

- Utilities

how to use require('util')

- File System

how to use require('fs')

- Operating System

how to use require('os')

- Debugger

how to use debugger
Some Global object
Available in all modules

- Console

how to use console

- Process

how to use process

- Exports

how to use exports

- require

how to use require()

- setTimeout

how to use setTimeout()

- clearTimeout

how to use clearTimeout()

- setInterval

how to use setInterval()

- clearInterval

how to use clearInterval()
Core Modules: usage
Net require('net')
- Asynchronous network wrapper. It can create server & Client.
- Following example program creates server. It can be connected
using Telnet/Putty & responds to all user provided data.
var sys = require("sys"),
net = require("net");
var server = net.createServer(function(stream) {
stream.setEncoding("utf8");
stream.addListener("connect", function() {
stream.write("Client connectedn");
});
stream.addListener("data", function(data) {
stream.write("Received from client: " + data);
stream.write(data);
});
});
server.listen(8000, "localhost");
Node Package Manager
NPM: npmjs.org
Node Package Manager (NPM)
- Node modules largely written in JavaScript which runs on the server
(executed by the V8 engine) rather than on the client side.
- These modules are registered in npm registry at registry.npmjs.org
- To use these modules while developing application, npm helps in
- installing Node js packages / Modules / Programs
- & linking their dependencies

- npm is a command line utility program
- npm is bundled and installed automatically with Node version 0.6.3 and
above
- On windows, after setting up environment variables npm command can
be executed from any desired location to install node packages
NPM Commands
npm -l
- display full usage info
npm <command> -h
- display quick help on command
- eg npm install -h
npm faq
- commonly asked questions
npm ls
- displays all versions of available packages installed on system, their
dependencies, in tree structure
…
npm install <module name>
- to install new modules
- on windows, command prompt should be running with admin rights
npm install <module name> -g
- to install new modules globally
- on windows at location C:Users<user>AppDataRoamingnpm
...
npm update
- update all listed packages to their latest version (in given folder)
- install missing packages
- removes old versions of packages
npm update -g
- update all listed global packages
npm update <pkg>
- update specific package
express js
Installing node module: express js
- express js
- Web application framework for node js
- Provides robust set of features to build single and multi page, &
hybrid web application

- installing express js on windows
- Start cmd with admin rights
- Make sure you have set up environment variable for node js
- Go to your project directory and type npm install express
...
- installing express as global package
- Previously we installed express for particular folder
- But usually we install it globally
- To install express globally, type npm install express -g

- On windows, this will install express in
C:Users<user>AppDataRoamingnpm
- express js is ready to use now
...
- Create a express project
- Inside project directory type express and enter
- This will create a project structure and will display created files,
what are dependencies and how to run project

- This is instructing to install dependencies by staying in same
directory and type npm install
...
- Run express server
- To run this newly created project, type node app

- Go to browser and type localhost:3000

And now you can start editing
code to make it the way you
want.
...
- While setting up project
- you can pass certain parameters to choose templating engine
and stylesheet engine

- for example, following command will create project with support
for ‘less’ stylesheet and ‘ejs’ templating
express -c less -e
Off course it need to install dependencies
References
http://en.wikipedia.org/wiki/V8_(JavaScript_engine)
http://stackoverflow.com/questions/6632606/where-does-node-js-fit-within-theweb-development-context
http://debuggable.com/posts/understanding-node-js:4bd98440-45e4-4a9a-8ef70f7ecbdd56cb
http://www.nodebeginner.org/
http://howtonode.org/
https://npmjs.org/
http://nodejs.org/
Book:
Node: Up & Running - Tom Hughes-Croucher & Mike Wilson (O’reilly)

More Related Content

PPTX
Introduction to Node js
Akshay Mathur
 
PDF
Introduction to node js - From "hello world" to deploying on azure
Colin Mackay
 
PPTX
Node js introduction
Joseph de Castelnau
 
PDF
Non-blocking I/O, Event loops and node.js
Marcus Frödin
 
PPT
RESTful API In Node Js using Express
Jeetendra singh
 
PPTX
NodeJS - Server Side JS
Ganesh Kondal
 
PPTX
Node js for beginners
Arjun Sreekumar
 
PPTX
Java script at backend nodejs
Amit Thakkar
 
Introduction to Node js
Akshay Mathur
 
Introduction to node js - From "hello world" to deploying on azure
Colin Mackay
 
Node js introduction
Joseph de Castelnau
 
Non-blocking I/O, Event loops and node.js
Marcus Frödin
 
RESTful API In Node Js using Express
Jeetendra singh
 
NodeJS - Server Side JS
Ganesh Kondal
 
Node js for beginners
Arjun Sreekumar
 
Java script at backend nodejs
Amit Thakkar
 

What's hot (20)

PPT
Nodejs Event Driven Concurrency for Web Applications
Ganesh Iyer
 
PDF
Node.js Explained
Jeff Kunkle
 
PDF
Node ppt
Tamil Selvan R S
 
PDF
An Introduction of Node Package Manager (NPM)
iFour Technolab Pvt. Ltd.
 
PDF
All aboard the NodeJS Express
David Boyer
 
PDF
Introduction to Node.js: What, why and how?
Christian Joudrey
 
PDF
Nodejs vatsal shah
Vatsal N Shah
 
PPTX
Introduction to Node.js
Vikash Singh
 
KEY
OSCON 2011 - Node.js Tutorial
Tom Croucher
 
PPTX
Intro to Node.js (v1)
Chris Cowan
 
PDF
Server Side Event Driven Programming
Kamal Hussain
 
KEY
Introduction to node.js
jacekbecela
 
PDF
Nodejs Explained with Examples
Gabriele Lana
 
KEY
Writing robust Node.js applications
Tom Croucher
 
PDF
Use Node.js to create a REST API
Fabien Vauchelles
 
PPTX
Nodejs intro
Ndjido Ardo BAR
 
PPTX
Introduction to node.js GDD
Sudar Muthu
 
PPT
Building your first Node app with Connect & Express
Christian Joudrey
 
PDF
NodeJS
LinkMe Srl
 
PDF
Node.js essentials
Bedis ElAchèche
 
Nodejs Event Driven Concurrency for Web Applications
Ganesh Iyer
 
Node.js Explained
Jeff Kunkle
 
An Introduction of Node Package Manager (NPM)
iFour Technolab Pvt. Ltd.
 
All aboard the NodeJS Express
David Boyer
 
Introduction to Node.js: What, why and how?
Christian Joudrey
 
Nodejs vatsal shah
Vatsal N Shah
 
Introduction to Node.js
Vikash Singh
 
OSCON 2011 - Node.js Tutorial
Tom Croucher
 
Intro to Node.js (v1)
Chris Cowan
 
Server Side Event Driven Programming
Kamal Hussain
 
Introduction to node.js
jacekbecela
 
Nodejs Explained with Examples
Gabriele Lana
 
Writing robust Node.js applications
Tom Croucher
 
Use Node.js to create a REST API
Fabien Vauchelles
 
Nodejs intro
Ndjido Ardo BAR
 
Introduction to node.js GDD
Sudar Muthu
 
Building your first Node app with Connect & Express
Christian Joudrey
 
NodeJS
LinkMe Srl
 
Node.js essentials
Bedis ElAchèche
 
Ad

Viewers also liked (20)

PDF
Node JS Express: Steps to Create Restful Web App
Edureka!
 
PPTX
Nodejs getting started
Triet Ho
 
PDF
Node.js – ask us anything!
Dev_Events
 
PDF
Building A Web App In 100% JavaScript with Carl Bergenhem
FITC
 
PPTX
Pengenalan Dasar NodeJS
alfi setyadi
 
PPTX
Node js overview
Eyal Vardi
 
PDF
Node js (runtime environment + js library) platform
Sreenivas Kappala
 
PDF
Mengembangkan Solusi Cloud dengan PaaS
The World Bank
 
PPT
single page application
Ravindra K
 
PPTX
Angular 2 with TypeScript
Cipriano Freitas
 
PPTX
Rits Brown Bag - TypeScript
Right IT Services
 
PDF
The Tale of 2 CLIs - Ember-cli and Angular-cli
Tracy Lee
 
PDF
Single-Page Web Application Architecture
Eray Arslan
 
PPTX
Angular 2 + TypeScript = true. Let's Play!
Sirar Salih
 
PDF
Introduction to Node.JS Express
Eueung Mulyana
 
PPTX
EAIESB TIBCO EXPERTISE
Vijay Reddy
 
PDF
Node Js, AngularJs and Express Js Tutorial
PHP Support
 
PPTX
Angular 2 with TypeScript
Shravan Kumar Kasagoni
 
PDF
Using Angular-CLI to Deploy an Angular 2 App Using Firebase in 30 Minutes
Tracy Lee
 
PDF
Creating an Angular 2 Angular CLI app in 15 Minutes Using MaterializeCSS & Fi...
Tracy Lee
 
Node JS Express: Steps to Create Restful Web App
Edureka!
 
Nodejs getting started
Triet Ho
 
Node.js – ask us anything!
Dev_Events
 
Building A Web App In 100% JavaScript with Carl Bergenhem
FITC
 
Pengenalan Dasar NodeJS
alfi setyadi
 
Node js overview
Eyal Vardi
 
Node js (runtime environment + js library) platform
Sreenivas Kappala
 
Mengembangkan Solusi Cloud dengan PaaS
The World Bank
 
single page application
Ravindra K
 
Angular 2 with TypeScript
Cipriano Freitas
 
Rits Brown Bag - TypeScript
Right IT Services
 
The Tale of 2 CLIs - Ember-cli and Angular-cli
Tracy Lee
 
Single-Page Web Application Architecture
Eray Arslan
 
Angular 2 + TypeScript = true. Let's Play!
Sirar Salih
 
Introduction to Node.JS Express
Eueung Mulyana
 
EAIESB TIBCO EXPERTISE
Vijay Reddy
 
Node Js, AngularJs and Express Js Tutorial
PHP Support
 
Angular 2 with TypeScript
Shravan Kumar Kasagoni
 
Using Angular-CLI to Deploy an Angular 2 App Using Firebase in 30 Minutes
Tracy Lee
 
Creating an Angular 2 Angular CLI app in 15 Minutes Using MaterializeCSS & Fi...
Tracy Lee
 
Ad

Similar to Node js (20)

PDF
Introduction to Node js for beginners + game project
Laurence Svekis ✔
 
PPTX
Node js training (1)
Ashish Gupta
 
PDF
OSDC.no 2015 introduction to node.js workshop
leffen
 
DOCX
unit 2 of Full stack web development subject
JeneferAlan1
 
PPTX
Nodejs web service for starters
Bruce Li
 
PPTX
Introducing Node.js in an Oracle technology environment (including hands-on)
Lucas Jellema
 
PPTX
concept of server-side JavaScript / JS Framework: NODEJS
Kongu Engineering College, Perundurai, Erode
 
PPTX
NodeJS guide for beginners
Enoch Joshua
 
PPTX
Introduction to node.js
Md. Sohel Rana
 
PPT
Node js beginner
Sureshreddy Nalimela
 
PDF
Ansible Automation to Rule Them All
Tim Fairweather
 
PPT
Ferrara Linux Day 2011
Gianluca Padovani
 
PPTX
Introduction to node.js
Su Zin Kyaw
 
PPTX
Introduction to node.js By Ahmed Assaf
Ahmed Assaf
 
PDF
Basic Understanding and Implement of Node.js
Gary Yeh
 
PPTX
Proposal
Constantine Priemski
 
PPTX
Nodejs
Vinod Kumar Marupu
 
PPT
nodejs_at_a_glance, understanding java script
mohammedarshadhussai4
 
PPTX
Nodejs
dssprakash
 
Introduction to Node js for beginners + game project
Laurence Svekis ✔
 
Node js training (1)
Ashish Gupta
 
OSDC.no 2015 introduction to node.js workshop
leffen
 
unit 2 of Full stack web development subject
JeneferAlan1
 
Nodejs web service for starters
Bruce Li
 
Introducing Node.js in an Oracle technology environment (including hands-on)
Lucas Jellema
 
concept of server-side JavaScript / JS Framework: NODEJS
Kongu Engineering College, Perundurai, Erode
 
NodeJS guide for beginners
Enoch Joshua
 
Introduction to node.js
Md. Sohel Rana
 
Node js beginner
Sureshreddy Nalimela
 
Ansible Automation to Rule Them All
Tim Fairweather
 
Ferrara Linux Day 2011
Gianluca Padovani
 
Introduction to node.js
Su Zin Kyaw
 
Introduction to node.js By Ahmed Assaf
Ahmed Assaf
 
Basic Understanding and Implement of Node.js
Gary Yeh
 
nodejs_at_a_glance, understanding java script
mohammedarshadhussai4
 
Nodejs
dssprakash
 

More from Rohan Chandane (13)

PDF
Agile Maturity Model, Certified Scrum Master!
Rohan Chandane
 
PDF
Agile & Scrum, Certified Scrum Master! Crash Course
Rohan Chandane
 
PDF
An Introduction To Testing In AngularJS Applications
Rohan Chandane
 
PDF
Agile :what i learnt so far
Rohan Chandane
 
PDF
Backbone js
Rohan Chandane
 
PPTX
Sencha / ExtJS : Object Oriented JavaScript
Rohan Chandane
 
PDF
TIBCO General Interface - CSS Guide
Rohan Chandane
 
PDF
Blogger's Park Presentation (Blogging)
Rohan Chandane
 
PDF
J2ME GUI Programming
Rohan Chandane
 
PDF
Parsing XML in J2ME
Rohan Chandane
 
PDF
J2ME RMS
Rohan Chandane
 
PDF
J2ME IO Classes
Rohan Chandane
 
PDF
Java2 MicroEdition-J2ME
Rohan Chandane
 
Agile Maturity Model, Certified Scrum Master!
Rohan Chandane
 
Agile & Scrum, Certified Scrum Master! Crash Course
Rohan Chandane
 
An Introduction To Testing In AngularJS Applications
Rohan Chandane
 
Agile :what i learnt so far
Rohan Chandane
 
Backbone js
Rohan Chandane
 
Sencha / ExtJS : Object Oriented JavaScript
Rohan Chandane
 
TIBCO General Interface - CSS Guide
Rohan Chandane
 
Blogger's Park Presentation (Blogging)
Rohan Chandane
 
J2ME GUI Programming
Rohan Chandane
 
Parsing XML in J2ME
Rohan Chandane
 
J2ME RMS
Rohan Chandane
 
J2ME IO Classes
Rohan Chandane
 
Java2 MicroEdition-J2ME
Rohan Chandane
 

Recently uploaded (20)

PPTX
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PPTX
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
PPTX
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PPTX
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
PPTX
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
PPTX
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
PDF
Biological Classification Class 11th NCERT CBSE NEET.pdf
NehaRohtagi1
 
DOCX
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
PPTX
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
PPTX
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
DOCX
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
Biological Classification Class 11th NCERT CBSE NEET.pdf
NehaRohtagi1
 
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 

Node js

  • 1. Node js with npm, installing express js @RohanChandane Last updated on 13th Oct 2013
  • 4. ... On windows machine, - Setting up environment variable is built in inside nodejs directory - after installation, type nodevars to install environment variable. nodevars.bat is a batch file responsible for setting it up
  • 5. What is Node / Node js? - Node is Command line tool - Download it and install - It runs javascript code by typing ‘node your-script-file.js’ - Hosted on V8 Javascript engine - uses V8 as standalone engine to execute javascript. - Server-side javascript - Node provides JavaScript API to access network & file system. - These JavaScript files runs on the server rather than on the client side - We can also write a server, which can be a replacement for something like the Apache web server
  • 6. ... - Uses event-driven I/O (non-blocking I/O) - is just a term that describes the normal asynchronous callback mechanisms. - In node.js you supply callback functions for all sorts of things, and your function is called when the relevant event occurs. - So that means, it works parallelly on different I/O operations. - eg. Code for reading from a file & reading values from a database can be executed one after another (since node js is single threaded), and it will wait for data to receive from file & database. Once it receives data, it will call callback function related to function call. - One language - to write server side and client side code - No need to learn server side language like Java & PHP
  • 7. Why Node 1. Efficiency - Response time = server-side script execution time + time taken for I/O operation - Node reduces the response time to the duration it takes to execute the slowest I/O query - Its mainly because ‘Single threaded - Event loop’ - Also called Event driven computing Architecture - There is a need for high performance web servers
  • 8. ... 2. JavaScript - JavaScript is universal language for web developers - Its single threaded - Its dynamic 3. Speed - Up till now, JavaScript was related to browser - We used it for DOM manipulation - and our favourite browser to execute javascript, is Chrome
  • 9. ... - Chrome uses V8 engine underneath to execute js - V8 is the fastest javascript execution engine - V8 was designed to run in Chrome’s multi-process model V8 engine - V8 is intended to be used both in a browser and as a standalone high-performance engine
  • 10. Asynchronous callback mechanisms 4. callbacks are invoked functions, which are initiating - I/O operations - writing to a socket - making a database query & not going to return the value immediately event loop 3. event occurs 1. registers callbacks 2. loop wait for events There's a single thread, and a single event loop, that handles all IO in node.js
  • 11. Writing Server-side js with Node Now, lets see how to write a server in JavaScript - creating 'server.js' var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888); - executing it: node server.js
  • 12. Passing function as parameter lets say function execute(someFunction, value) { someFunction(value); } execute(function(word){ console.log(word) }, "Hello"); can also be written function say(word) { console.log(word); } function execute(someFunction, value) { someFunction(value); } execute(say, "Hello");
  • 13. Understanding server.js var http = require("http"); function onRequest(request, response) { console.log("Callback invoked"); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } 1 2 http.createServer(onRequest).listen(8888); console.log("Server started"); 3 4 single thread
  • 14. ... This ‘server.js’ program executes in following order 1. registers callbacks onRequest 2. loop wait for events listen(8888) 3. event occurs Browser requests - localhost:8888 4. callbacks are invoked function onRequest() gets execute
  • 15. Some Basic Core Modules Node has several modules compiled into the binary. Defined in node's source in the lib/ folder. To load use require('modules identifier') - HTTP how to use require('http') - Net how to use require('net') - DNS how to use require('dns') - Events how to use require('events') - Utilities how to use require('util') - File System how to use require('fs') - Operating System how to use require('os') - Debugger how to use debugger
  • 16. Some Global object Available in all modules - Console how to use console - Process how to use process - Exports how to use exports - require how to use require() - setTimeout how to use setTimeout() - clearTimeout how to use clearTimeout() - setInterval how to use setInterval() - clearInterval how to use clearInterval()
  • 17. Core Modules: usage Net require('net') - Asynchronous network wrapper. It can create server & Client. - Following example program creates server. It can be connected using Telnet/Putty & responds to all user provided data. var sys = require("sys"), net = require("net"); var server = net.createServer(function(stream) { stream.setEncoding("utf8"); stream.addListener("connect", function() { stream.write("Client connectedn"); }); stream.addListener("data", function(data) { stream.write("Received from client: " + data); stream.write(data); }); }); server.listen(8000, "localhost");
  • 19. NPM: npmjs.org Node Package Manager (NPM) - Node modules largely written in JavaScript which runs on the server (executed by the V8 engine) rather than on the client side. - These modules are registered in npm registry at registry.npmjs.org - To use these modules while developing application, npm helps in - installing Node js packages / Modules / Programs - & linking their dependencies - npm is a command line utility program - npm is bundled and installed automatically with Node version 0.6.3 and above - On windows, after setting up environment variables npm command can be executed from any desired location to install node packages
  • 20. NPM Commands npm -l - display full usage info npm <command> -h - display quick help on command - eg npm install -h npm faq - commonly asked questions npm ls - displays all versions of available packages installed on system, their dependencies, in tree structure
  • 21. … npm install <module name> - to install new modules - on windows, command prompt should be running with admin rights npm install <module name> -g - to install new modules globally - on windows at location C:Users<user>AppDataRoamingnpm
  • 22. ... npm update - update all listed packages to their latest version (in given folder) - install missing packages - removes old versions of packages npm update -g - update all listed global packages npm update <pkg> - update specific package
  • 24. Installing node module: express js - express js - Web application framework for node js - Provides robust set of features to build single and multi page, & hybrid web application - installing express js on windows - Start cmd with admin rights - Make sure you have set up environment variable for node js - Go to your project directory and type npm install express
  • 25. ... - installing express as global package - Previously we installed express for particular folder - But usually we install it globally - To install express globally, type npm install express -g - On windows, this will install express in C:Users<user>AppDataRoamingnpm - express js is ready to use now
  • 26. ... - Create a express project - Inside project directory type express and enter - This will create a project structure and will display created files, what are dependencies and how to run project - This is instructing to install dependencies by staying in same directory and type npm install
  • 27. ... - Run express server - To run this newly created project, type node app - Go to browser and type localhost:3000 And now you can start editing code to make it the way you want.
  • 28. ... - While setting up project - you can pass certain parameters to choose templating engine and stylesheet engine - for example, following command will create project with support for ‘less’ stylesheet and ‘ejs’ templating express -c less -e Off course it need to install dependencies