You are on page 1of 126

JavaScript.

next
ES6

CSC 3916
JavaScript
History
3
JavaScript is a Client-side, Simple and Power to
front-end mobile and flexible manipulate the
scripting desktop DOM
language technology
developed by
Netscape for
dynamic content

JavaScript Lightweight, but with


limited capabilities

History Can be used as object-


oriented language
Embedded in your
HTML page
Interpreted by the Web
browser

1997
ECMAScript 1
1998 2009
ECMAScript 2 ECMAScript 5
2005 - 2007
1999 2014
ECMAScript 3 ECMAScript 4 - Abandoned ECMAScript 6?

2014
1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013

1997 2015
Terminology

JavaScript/ JSON / Document


Object Model/ Browser Events/
DOM Level 0 / Cascading
Style Sheets/ DOM Level 2/
void / Closures / function /
object / literals/ this/ ajax /
effects / animation
JSON- definition
1. JavaScript Object Notation is a lightweight data-interchange format
closure- definition
1. is a function instance coupled with the local variables from its
environment that are necessary for it execution.
1. Declare local
variable

2. Establish timer
<script>
$(function() {
var local = 1;
window.SetInterval(function() {
alert(local);
local++; 3. Local variable
} incremented
});
</script>
CSS- definition
1. Cascading Style Sheets is a style sheet language used to describe the
presentation semantics of a document written in a markup language
AJAX- definition
1. Asynchronous JavaScript and Xml is a group of interrelated web
development techniques used on the client-side to create interactive
web applications.
i. Html/XHtml and CSS for presentation
ii. DOM for dynamic display of and interaction with data
iii. Xml and Xslt for the interchange, and manipulation and display,
of data, respectively
iv. XmlHttpRequest object for asynchronous communication
v. JavaScript to bring them all together
JavaScript
Fundamentals
Same as Java/C++/C-
style langs

for-loops:
for (let i = 0; i < 5; i++) { … }
while-loops:
while (notFinished) { … }
comments:
// comment or /* comment */
conditionals (if statements):
if (...) {
...
} else {
...
}
If Statements

if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
While Loops

while (condition) {
statements;
}

do {
statements;
} while (condition);
Comments

JavaScript Comments HTML Comments


These comments must be within a script <!-- All of your comments here… -->
// begins a single line comment
• These can start anywhere on the line, but
the remainder of the line becomes a
comment
/* All of your comments here… */
• Everything between the start and end
comment markers are comments
• Can be on a single line or span many…
Semicolon

 With traditional programming languages, like C++ and


Java, each code statement has to end with a semicolon (;).
 Many programmers continue this habit when writing
JavaScript, but in general, semicolons are optional!
 Semicolons are required if you want to put more than one
statement on a single line.
Functions
One way of defining a JavaScript function is with the following syntax:

function name() {
statement;
statement;
...
}
script.js

function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}

hello();
hello();

Console output
script.js

function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}

hello();
hello();

The browser "executes" the


function definition first, but
that just creates the hello
function (and it doesn't run
the hello function), similar
to a variable declaration.
Console output
script.js

hello();
hello();

function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}

Q: Does this work?


script.js

hello();
hello();

function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}
A: Yes, for this particular syntax.
This works because function
declarations are "hoisted" (mdn).
You can think of it as if the
definition gets moved to the top of
the scope in which it's defined Console output
(though that's not what actually happens).
script.js

hello();
hello();

function hello() {
console.log('Hello!');
console.log('Welcome to JavaScript');
}
Caveats:
- There are other ways to define
functions that do not get hoisted;
we'll visit this once we graduate
from JS
- Try not to rely on hoisting when
coding. It gets bad.
Console output
Variables: var, let, const
Declare a variable in JS with one of three keywords:

// Function scope variable


var x = 15;
// Block scope variable
let fruit = 'banana';
// Block scope constant; cannot be reassigned
const isHungry = true;

You do not declare the datatype of the variable before using it ("
dynamically typed")
Function parameters
function printMessage(message, times) {
for (var i = 0; i < times; i++) {
console.log(message);
}
}

Function parameters are not declared with var, let, or const


Understanding var
function printMessage(message, times) {
for (var i = 0; i < times; i++) {
console.log(message);
}
console.log('Value of i is ' + i);
}
printMessage('hello', 3);

Q: What happens if we try to print "i" at


the end of the loop?
Understanding var
function printMessage(message, times) {
for (var i = 0; i < times; i++) {
console.log(message);
}
console.log('Value of i is ' + i);
}
printMessage('hello', 3);
The value of "i" is readable outside of
the for-loop because variables
declared with var have function
scope.
Function scope with var
var x = 10;
if (x > 0) {
var y = 10;
}
console.log('Value of y is ' + y);
 Variables declared with "var" have function-level scope and do not
go out of scope at the end of blocks; only at the end of functions
 Therefore you can refer to the same variable after the block has
ended (e.g. after the loop or if-statement in which they are
declared)
Function scope with var

But you can't refer to a variable outside of the function in which it's
declared.
Understanding let
function printMessage(message, times) {
for (let i = 0; i < times; i++) {
console.log(message);
}
console.log('Value of i is ' + i);
}
printMessage('hello', 3);

Q: What happens if we try to print "i" at


the end of the loop?
Understanding let
function printMessage(message, times) {
for (let i = 0; i < times; i++) {
console.log(message);
}
console.log('Value of i is ' + i);
}
printMessage('hello', 3);
let has block-
scope so this
results in an error
Understanding const
let x = 10;
if (x > 0) {
const y = 10;
}
console.log(y); // error!

Like let, const also has block-scope, so accessing the variable


outside the block results in an error
Understanding const
const y = 10;
y = 0; // error!
y++; // error!
const list = [1, 2, 3];
list.push(4); // OK

const declared variables cannot be reassigned.


However, it doesn't provide true const correctness, so you can still
modify the underlying object
 (In other words, it behaves like Java's final keyword and not C++'s
const keyword)
Contrasting with let
let y = 10;
y = 0; // OK
y++; // OK
let list = [1, 2, 3];
list.push(4); // OK

let can be reassigned, which is the difference between const and let
Variables best practices
 Use const whenever possible.
 If you need a variable to be reassignable, use let.

- Don't use var.


- You will see a ton of example code on the internet with var since const and
let are relatively new.
 However, const and let are well-supported, so there's no reason not to use
them.

(This is also what the Google and AirBnB JavaScript Style Guides recommend.)
Variables best practices
 Use const whenever possible.
 If you need a variable to be reassignable, use let.

- Don't use var.


- You will see a ton of example code on the internet with var since const and
let are relatively new.
 However, const and let are well-supported, so there's no reason not to use
them.
(This is also what the Google and AirBnB JavaScript Style Guides recommend.)

Aside: The internet has a ton of


misinformation about JavaScript!
Including several "accepted" StackOverflow answers,
tutorials, etc. Lots of stuff online is years out of date.
Tread carefully.
Types
JS variables do not have types, but the values do.

There are six primitive types (mdn):


 Boolean : true and false
 Number : everything is a double (no integers)
 String: in 'single' or "double-quotes"
 Symbol: (skipping this today)
 Null: null: a value meaning "this has no value"
 Undefined: the value of a variable with no value assigned

There are also Object types, including Array, Date, String (the object
wrapper for the primitive type), etc.
Numbers
const homework = 0.45;
const midterm = 0.2;
const final = 0.35;
const score =
homework * 87 + midterm * 90 + final * 95;
console.log(score); // 90.4
Numbers
const homework = 0.45;
const midterm = 0.2;
const final = 0.35;
const score =
homework * 87 + midterm * 90 + final * 95;
console.log(score); // 90.4

 All numbers are floating point real numbers. No integer type.


 Operators are like Java or C++.
 Precedence like Java or C++.
 A few special values: NaN (not-a-number), +Infinity, -Infinity
 There's a Math class: Math.floor, Math.ceil, etc.
Strings
let snack = 'coo';
snack += 'kies';
snack = snack.toUpperCase();
console.log("I want " + snack);
Strings
let snack = 'coo';
snack += 'kies';
snack = snack.toUpperCase();
console.log("I want " + snack);

 Can be defined with single or double quotes


 Many style guides prefer single-quote, but there is no functionality difference
 Immutable
 No char type: letters are strings of length one
 Can use plus for concatenation
 Can check size via length property (not function)
Strings

var s = "Connie Client";


var fName = s.substring(0, s.indexOf(" ")); //
"Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant';
 methods: charAt, charCodeAt,
fromCharCode, indexOf, lastIndexOf,
replace, split, substring,
toLowerCase, toUpperCase
 charAt returns a one-letter String (there is no char type)
 Strings can be specified with "" or ''
• 1 + 1 is 2, but "1" + 1 is "11"
Strings
var count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10
bananas, ah ah ah!"
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseFloat("booyah"); // NaN

var s = "the quick brown fox";


var a = s.split(" "); // ["the", "quick", "brown",
"fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
Boolean
 There are two literal values for boolean: true and false that behave as
you would expect
 Can use the usual boolean operators: && || !

let isHungry = true;


let isTeenager = age > 12 && age < 20;

if (isHungry && isTeenager) {


pizza++;
}
Boolean
 Non-boolean values can be used in control statements, which get converted
to their "truthy" or "falsy" value:
 null, undefined, 0, NaN, '', "" evaluate to false
 Everything else evaluates to true

if (username) {
// username is defined
}
Boolean

var iLike190M = true;


var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /*
true */ }
if (0) { /* false */ }
JavaScript's == and != are basically broken:
they do an implicit type conversion before
the comparison.

'' == '0' // false


'' == 0 // true

Equality 0 == '0' // true


NaN == NaN // false
[''] == '' // true
false == undefined // false
false == null // false
null == undefined // true
Instead of fixing == and != , the ECMAScript
standard kept the existing behavior but added ===
and !==

'' === '0' // false


'' === 0 // false
0 === '0' // false

Equality
NaN === NaN // still weirdly false
[''] === '' // false
false === undefined // false
false === null // false
null === undefined // false

Always use === and !== and don't use == or !=


Null and Undefined
What's the difference?
 null is a value representing the absence of a value, similar to null
in Java and nullptr in C++.
 undefined is the value given to a variable that has not been a
value.
Null and Undefined
What's the difference?
 null is a value representing the absence of a value, similar to null
in Java and nullptr in C++.
 undefined is the value given to a variable that has not been a
value.
 … however, you can also set a variable's value to undefined
Arrays
Arrays are Object types used to create lists of data.

// Creates an empty list


let list = [];
let groceries = ['milk', 'cocoa puffs'];
groceries[1] = 'kix';

 0-based indexing
 Mutable
 Can check size via length property (not function)
Arrays

var a = ["Stef", "Jason"]; // Stef, Jason


a.push("Brian"); // Stef, Jason, Brian
a.unshift("Kelly"); // Kelly, Stef, Jason, Brian
a.pop(); // Kelly, Stef, Jason
a.shift(); // Stef, Jason
a.sort(); // Jason, Stef
array serves as many data structures: list, queue, stack, ...
 methods: concat, join, pop, push, reverse, shift,
slice, sort, splice, toString, unshift
 push and pop add / remove from back
 unshift and shift add / remove from front
 shift and pop return the element that is removed
JavaScript Statements

<script type="text/javascript">

var a = 10;
var b = 11;
var c;
c = a + b;
alert(‘The answer is’ + c);

</script>
JavaScript Variables

 Rules for variable names:


 Variable names are case sensitive
 They must begin with a letter or the underscore character
 strname – STRNAME (not same)
 All variables have
 Name
 Type – JavaScript is loosely typed
 Value or “null”
 To declare a variable
 var variableName
 Beware of reserved words:
 E.g., ‘if’, ‘Document’, ‘Math’, etc.
Arithmetic
Operations
Assignment
Operations
Comparison
Operations
Logical
Operations
 alert("Hello!");
Dialogs  confirm("Delete files?");
 var name=prompt("Your
name?", ”Alan Turing");
var myObject = new Object();
 Unlike Java/C# the object “properties” are
created dynamically as needed.

JavaScript myObject.make = ”Chevy";


myObjected.purchased = new Date(2018,1,1);
Objects  We don’t need to declare these properties prior to
assigning them
 With great power comes great responsibility
myObjected.purchsed = new Date(2018,1,1);
 No warning that we made a mistake
Object[propertyNameExpression]

General  The following are equivalent:

Property myObject.make;
Reference myObject['make'];
Op var p = 'make';
myObject[p];
Using an object literal is the preferred
method, over the multiple assignment
means of building an object.
var ride = {

Object make : 'Ford',


model : 'Mustang',
Literals year : 2005,
purchased : new Date(2005,1,1),
JSON owner : { name: 'Shawn McCarthy' }
};

var myArray = [1,2,3,4,5,6,7];


When the var keyword is used at the top
level script, outside the body of a
containing function it is implicitly made
on the window instance.
Top Level Scope == Window Scope

Window
var foo = bar;
Properties? window.foo = bar;
foo = bar;

In each case a window property foo is


created.
Functions in JavaScript are considered objects. Like
other objects in JavaScript functions are defined by a
JavaScript constructor.

Assigned to Variables

Assigned as a property of an object


Functions are
Objects? Passed as a parameter

Returned as a function result

Created using literals


JavaScript functions are not named entities,
functions are referenced only when they
are assigned to variables, properties, or
parameters.
function doSomething() {
alert('Did something');
Functions }

are The function keyword here creates a


Objects? function instance and assigns it to a
window property
doSomething = function() {
alert('Did something');
}
Passing a function as a parameter is no
different than pasing any other value.
function doSomething() {
alert('Did something');
Functions }

as callbacks
In this case the timer function “calls back” to
function in our own code

setTimeout(doSomething, 5000);
In JavaScript the object referenced by this
(function context) is determined not by how
the function is declared but by how it is
invoked.
var ride = {
make: ‘Chevy',

Functions model: ‘Camaro',


year: 2018,
as callbacks getString: function() { return this.year + ' ' +
this.make + ' ' + this.model; }
};

var car = ride.getString(); // ‘2018 Chevy


Camaro'
In JavaScript we can set the context through apply() or call()
The call() method invokes the function specifying as its first
parameter the object to serve as the function context
var make = 'bmw';
var o1 = { make: 'ford' };
var o2 = { make: 'chevy' };
function getString() {

Functions return this.make;


}
as callbacks o1.getAnotherString = getString;
alert(getString()); //bmw
alert(o1.getAnotherString()); //ford
alert(getString.call(o1)); //ford
alert(getString.apply(o2)); //chevy
o1.getAnotherString.call(o2); //chevy
Closures

A CLOSURE IS A WHEN A FUNCTION IS THE ABILITY FOR


FUNCTION INSTANCE DECLARED, IT HAS THE CALLBACK FUNCTIONS
COUPLED WITH THE ABILITY TO REFERENCE TO REFERENCE THE
LOCAL VARIABLES FROM ANY VARIABLE IN ITS LOCAL VARIABLES IN
ITS ENVIRONMENT THAT SCOPE AT THE POINT OF EFFECT WHEN THEY
ARE NECESSARY FOR ITS DECLARATION. THESE WERE DECLARED CAN BE
EXECUTION VARIABLES ARE CARRIED A LITTLE CONFUSING BUT
ALONG WITH THE ESSENTIAL CONCEPT
FUNCTION EVEN AFTER
THE POINT OF
DECLARATION HAS GONE
OUT OF SCOPE, CLOSING
THE DECLARATION.
function app (x) {
return function (y) {
return x + y;
};
}
Closures var appHello = app('hello ');
var world = appHello('world');
alert(world); // hello world;
ES6 Variables
ES6 Variables
 ES6 introduces new ways to declare variables:
 let – creates a scope variable
Accessible only in its scope

for(let number of [1, 2, 3, 4]){


console.log(number);
}
//accessing number here throws exception

 const – creates a constant variable


 Its value is read-only and cannot be changed

const MAX_VALUE = 16;


MAX_VALUE = 15; // throws exception
ES6 Variables
LIVE DEMO
for-of loop
For-of loop
 The for-of loop iterates over the values
Of an array
let sum = 0;
for(let number of [1, 2, 3])
sum+= number;

 Of An iteratable object
function* generator(maxValue){
for(let i = 0; i < maxValue; i+=1){
yield i;
}
}
let iter = generator(10);
for(let val of iter()){
console.log(val);
}
For-of loop
LIVE DEMO
Templated String
Templated Strings in ES6

 ES6 supports templated strings


i.e. strings with placeholders:

let people = [new Person('Doncho', 'Minkov'), … ];


for(let person of people){
log(`Fullname: ${person.fname} ${person.lname}`);
}

 Templates escape the strings


 They do not call eval
Classes and
Inheritance
THE WAY OF OOP IN ES6
Classes and Inheritance in ES6
 ES6 introduces classes and a way to create classical OOP

class Person extends Mammal{


constructor(fname, lname, age){
super(age);
this._fname = fname;
this._lname = lname;
}
get fullname() {
//getter property of fullname
}
set fullname(newfullname) {
//setter property of fullname
}
// more class members…
}
Classes and Inheritance in ES6
 ES6 introduces classes and a way to create classical OOP
class Person extends Mammal{
constructor(fname, lname, age){
super(age);
this._fname = fname; Constructor of the class
this._lname = lname;
}
get fullname() {
//getter property of fullname
}
set fullname(newfullname) {
//setter property of fullname
}
// more class members…
}
Classes and Inheritance in ES6
 ES6 introduces classes and a way to create classical OOP
class Person extends Mammal{
constructor(fname, lname, age){
super(age);
this._fname = fname; Constructor of the class
this._lname = lname;
}
get fullname() {
//getter property of fullname
}
Getters and setters
set fullname(newfullname) {
//setter property of fullname
}
// more class members…
}
Classes and Inheritance in ES6

LIVE DEMO
Arrow Functions
ALSO CALLED LAMBDA EXPRESSIONS
Arrow Functions
 Arrow functions
easify the creation
of functions:
Arrow Functions
 Arrow functions
easify the creation
of functions:

numbers.sort(function(a, b){
return b – a;
});
Arrow Functions
 Arrow functions
easify the creation
of functions:

numbers.sort(function(a, b){
return b – a;
});
Becomes

numbers.sort((a, b) => b –
a);
Arrow Functions
 Arrow functions numbers.sort(function(a, b){
easify the creation return b – a;
of functions: });
Becomes

numbers.sort((a, b) => b –
a);

var fullnames =
people.filter(function (person) {
return person.age >= 18;
}).map(function (person) {
return person.fullname;
});
Arrow Functions
 Arrow functions numbers.sort(function(a, b){
easify the creation return b – a;
of functions: });
Becomes

numbers.sort((a, b) => b –
a);
var fullnames =
people.filter(function (person) {
return person.age >= 18;
}).map(function (person) {
return person.fullname; Becomes
});

var fullnames2 =
people.filter(p => p.age >= 18)
.map(p => p.fullname);
Arrow Functions
LIVE DEMO
Object Literals
Object Literals
 ES6 adds a new feature (rule) to the way of defining properties:
 Instead of
let name = 'Doncho Minkov',
age = 25;
let person = {
name: name,
age: age
};

 We can do just:
let name = 'Doncho Minkov';
let person = {
name,
age
};
Object Literals
LIVE DEMO
Destructuring
Assignments
Destructuring Assignments
 Destructuring assignments allow to set values to objects in an easier way:
 Destructuring assignments with arrays:

var [a,b] = [1,2]; //a = 1, b = 2


var [x, , y] = [1, 2, 3] // x = 1, y = 3
var [first, second, ...rest] = people;

 Swap values: [x, y] = [y, x]

 Result of method:
function get(){ return [1, 2, 3]; }
var [x, y] = get();
Destructuring Assignments
 Destructuring assignments allow to set values to objects in an easier way:
 Destructuring assignments with objects:

var person = {
name: 'Doncho Minkov',
address: {
city: 'Sofia',
street: 'Aleksander Malinov'
}
};

var {name, address: {city}} = person;


Destructuring
Assignments
LIVE DEMO
Maps and Sets
Maps and Sets

 ES6 supports maps and sets natively


 They do pretty much the same as associative arrays, but in
cleaner way:

let names = new Set();


names.add('Doncho');
names.add('Nikolay');
names.add('Ivaylo');
names.add('Evlogi');
names.add('Doncho'); // won't be added
Maps and Sets
LIVE DEMO
ES6 Modules
ES6 Modules
 ES6 supports modules
 A way to write JavaScript in different files
Each file has its own scope (not the global)
Each file decides what to export from its module
 Export the objects you want from a module:

module.exports = { persons.js
Person: Person,
Mammal: Mammal
}
 To use the module in another file:
import classes from './persons'
import {Mammal, Person} form '.persons'
ES6 Modules
LIVE DEMO
Simple Node
App
WALK THROUGH
Build an App

 We will build an app that will:


 Import necessary modules
 Create a Server instance
 Attach listeners to the request event of the server object
 Parse request body and headers
 Sending Response to the client.
 Handle error events at request and response streams.
HTTP Module

 What is HTTP?
 http in Node.js is an inbuilt module that allows
client-server communication via HTTP protocol.
This module provides an interface to create either
an HTTP client or HTTP server that can
communicate with other HTTP servers or clients.
 And to make this communication space efficient,
an http module provides streaming of data using
stream interface. And since stream passes data in
chunks, that means Node.js never buffers the entire
request or response at once in the memory. We will
come to streams soon.
 So for our app, we will use this http interface to
create an HTTP server that will listen to a
particular port and give data back to the user.
Require

 How does require work?


 At runtime when Node.js invokes a require call
(require(‘./path/to/fileName’), it searches for a file with a name
the same as what’s provided in the only parameter to the
require function call.
 And once the file name matches, Node.js checks for 3 types of
extensions:
 .js — Node.js looks for “fileName.js” at the specified path to load
as js script.
 .json — If Node.js finds “filename.json” file at the specified path it
loads a file with the name corresponding to the value of the ‘main’
key in the JSON file.
 .node — Node.js loads binary addons with name fileName.node at
the specified path.
Importing a Module

 To use either the http server or client you must


require http module.
 var http = require(“http”);
 For loading an instance of a particular module in our
runtime, Node.js provides us a require variable which is
globally accessible. We use that globally
defined require variable and tell Node to load
the http module (by passing 'http' as the only param to
the require function call).
Create a Server

Now that we have included


the http module, we need To createServer method, This createServer method
to create an HTTP web we pass a callback function returns a server object that
server object. This can be which is called every time we store in the
done by using a request is received on the variable app. This server
the createServer method on server. object is an event emitter.
the http module.
Event Emitter?

Let’s look a bit into the Much of the Node.js core APIs are built Let us see an example to get the hang of
named event and emitter objects. around an event-driven architecture. it.
Certain kinds of objects (called
“emitters”) can cause some Function
(“listeners”) to be called by emitting any
“named” events.
Emitter
Example
Emitter (subset)

 Our web server object is also like all other emitter objects
implementing event emitter interfaces. It also emits different
kinds of named events.
 Some of them are the following:
 connect— raised for all the ‘connect’ request by the HTTP
client.
 connection — Emitted when a new TCP stream is established.
Provide access to the socket established.
 request — Emitted for Each request from the client (We would
listen here).
 upgrade — emitted each time a client requests an upgrade of
the protocol (can be HTTP version).
 Now since our server needs to listen to the incoming request, we will listen
to the request event of our HTTP server.

Listen  In the 3rd line, a listener function is attached to listen to all the request
events on our server object.
 The request event provides the listener function with 2 parameters which
are:
 request — an instance of http.incomingMessage object and
 response — an instance of http.ServerResponse object.
 These request and response objects have properties and methods that they
inherit from the http.incomingMessage and http.ServerResponse classes,
respectively.
Parse

 Now that we have access to request and response object…


 The first few things that you might want to know about incoming
requests are the URL, method, and Headers. Node.js makes it
very easy by attaching them as properties to the request object
(passed as the first parameter for the listener of request event).
 You can de-structure the request object to get them out like this:
 const {headers, url, method } = request;
 headers passed in request are present as an independent object
inside the request object (secret : they are all in lower-case).
 After looking at the http method, in case of a PUT or POST
request, we are interested in looking at the data sent in the request
body.
Read Data

 The request object that’s passed into the handler also implements
the readable stream interface. This means that our request object is a
stream that can be listened to or piped elsewhere to grab the data
that is flowing into it. We will also grab the data right out of
the request stream by listening to the stream’s data and end events.
 Different kinds of data may be passed to our server, but to keep it
simple we will be passing only the string in the body.
 To use that data we need to parse it, so we will be using
the data and endevent of the readable stream which is implemented
by our request object as mentioned earlier.
 On each data event, the readable stream passes data as a buffer
chunk.We will be appending all the chunks in an empty array. And
at the end event we will concat and stringify the array to get the
cumulative body.
Sending a Response

 After collecting data from the HTTP request we need to


give an appropriate response to the client. But since
the request object implements a readable stream only, we
need a writable stream where we can write out our
response.
 Response Object — a writable stream
 For doing so, Node.js provide us with a 2nd parameter that
is the response object to the request event listener.
 By using the response object, we can set HTTP status code,
set headers, and write content in the write stream of the
response object.
Status Code

Although if you do not set the response code explicitly, then Node.js
itself sets it to 200. But as complexity increases you will want to set
the desired statusCode of the HTTP response.
Headers

 You can set, get and remove headers to the response


using setHeader(name, value), getHeader(name),
and removeHeader(name) API.
Header (Explicit)

 To set headers and status code explicitly, we have


a response.writeHead()method.
 Since the response object is a writable
stream object, we just need to use write
stream methods to write data chunks into
the HTTP response object

Write a
Response

After writing to the response stream, we need to close


the stream so that Node.js gets to know that it’s time
to send the response back to the client.
.end() method allows us
to close the HTTP connection that was set up at the
time of the request hitting our server.
Errors

 But, what will happen when our server encounters an


exception?
 We need to hear the error events
of request and response streams. An error event is raised every
time an exception occurs. You can try to avoid it but they do
come and we have to catch and handle them properly.
 But how?
 We will handle them by attaching error handlers to
the error events of request and response streams.
 Here we are catching all the error events
of request and response streams and just logging
them into the console. You can also
use util instead of the console in the production
environment (although in production it’s advised
to inspect errors properly).

Errors
Complete

1. Import necessary modules


2. create a Server instance
3. Attach listeners to
the request event of server object
4. Parse request body and headers
5. Write the response to response
Stream
6. Handle error events at request and
response streams.
Receive Requests

 To do so we will use the .listen method of our HTTP server


object, .listen(PORT , CB).
 @params PORT is the port number where we want our server
to listen.
 @params Callback is called once the server starts listening.
Receive
Requests
 Let us run our Node.js app:
 node app.js and hit our server with the
Run it following curl on a terminal:
 curl -d “Hello World” -H “Content-Type:
text” -X POST http://localhost:8008

You might also like