Introduction to

Agenda

  1. JS on Browser? What is Node.js?
  2. Processing models & inside look
  3. Blocking and Non-blocking - code compare
  4. About EventLoop
  5. Create HTTP Server
  6. Who is using Node.js and Hosting solutions

What is Node.js?

  • Open source & cross-platform project.
  • Build on Chrome's JavaScript runtime environment.
  • Event driven & Non-blocking IO.
  • Real time apps.
  • Single threaded.
  • Build in Async IO, HTTP/s, file-system etc.
  • Ability to do JavaScript on server.
  • Act as a web server.

Processing Model

Traditional Web Application

Architecture

Compare code

Blocking Sync VS Non-blocking Async

const fs = require('fs');

const data = fs.readFileSync('/file.md'); // blocks here until file is read

console.log(data);

// moreWork(); will run after console.log

Synchronous file read:

Asynchronous file read:

const fs = require('fs');

fs.readFile('/file.md', (error, data) => {

  if (error) throw error; // throw error or use logger to log
  console.log(data);
});

// moreWork(); will run before console.log

Compare code

Warning on mixing Blocking and Non-blocking code

const fs = require('fs');

fs.readFile('/file.md', (err, data) => {

  if (err) throw err;
  console.log(data);
});

fs.unlinkSync('/file.md'); // File will get delete first

Problem:

Solution: Non-blocking with correct order of execution

const fs = require('fs');

fs.readFile('/file.md', (readFileErr, data) => {

  if (readFileErr) throw readFileErr;
  console.log(data);

  fs.unlink('/file.md', (unlinkErr) => {
    if (unlinkErr) throw unlinkErr;
  });
});

What is Event Loop?

What is Event Loop?

setImmediate() VS setTimeout()

setImmediate():

• Executes once the current Poll phase completes

setTimeout():

• Schedule a script to be run after a minimum threshold in ms elapsed

Timers in Node.js

SetTimeout Function

The only guarantee is that the timeout will not execute sooner than the declared timeout interval.

setTimeout()

• Schedule a script to be run after a minimum threshold in ms elapsed

function myFunc(arg) {
  console.log(`arg was => ${arg}`);
}

setTimeout(myFunc, 1500, 'Hello');

Timers in Node.js

SetIntermediate Function

setIntermediate()

• Code will execute after any I/O operations in the current event loop

• And before any timers scheduled for the next event loop

console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
before immediate
after immediate
executing immediate: so immediate

Timers in Node.js

Process.NextTick Function

process.nextTick()

• Will run before any Immediates that are set

• Will run before any scheduled I/O

• It non-clearable, meaning once code has been scheduled to execute, the execution cannot be stopped

Timers in Node.js

SetInterval Function

setInterval()

• Infinite loop

Same rules apply which applies for setTimeout()

function intervalFunc() {
  console.log('Cant stop me now!');
}

setInterval(intervalFunc, 1500);

Timers in Node.js

Cleaning the future

const timeoutObj = setTimeout(() => {
  console.log('timeout beyond time');
}, 1500);

const immediateObj = setImmediate(() => {
  console.log('immediately executing immediate');
});

const intervalObj = setInterval(() => {
  console.log('interviewing the interval');
}, 500);

clearTimeout(timeoutObj);
clearImmediate(immediateObj);
clearInterval(intervalObj);

Script not within an IO cycle

bounded by the performance of the process

// timeout_vs_immediate.js

setTimeout(() => {
  console.log('timeout');
}, 0);

setImmediate(() => {
  console.log('immediate');
});

Input

Output

$ node timeout_vs_immediate.js
timeout
immediate

$ node timeout_vs_immediate.js
immediate
timeout

Script within an IO cycle

Immediate callback will always executed first

// timeout_vs_immediate.js

const fs = require('fs');

fs.readFile(__filename, () => {

  setTimeout(() => {
    console.log('timeout');
  }, 0);

  setImmediate(() => {
    console.log('immediate');
  });
});

Input

Output

$ node timeout_vs_immediate.js
immediate
timeout

$ node timeout_vs_immediate.js
immediate
timeout

Create HTTP Server

const http = require('http');

http.createServer((request, response) => {
  const { headers, method, url } = request;
  let body = [];
  request.on('error', (err) => {
    console.error(err);
  }).on('data', (chunk) => {
    body.push(chunk);
  }).on('end', () => {
    body = Buffer.concat(body).toString();
    // BEGINNING OF NEW STUFF

    response.on('error', (err) => {
      console.error(err);
    });

    response.statusCode = 200;
    response.setHeader('Content-Type', 'application/json');
    // Note: the 2 lines above could be replaced with this next one:
    // response.writeHead(200, {'Content-Type': 'application/json'})

    const responseBody = { headers, method, url, body };

    response.write(JSON.stringify(responseBody));
    response.end();
    // Note: the 2 lines above could be replaced with this next one:
    // response.end(JSON.stringify(responseBody))

    // END OF NEW STUFF
  });
}).listen(8080);

Companies using Node.js

visit: https://nodejs.org/industry

Node.js hosting companies

visit: https://github.com/joyent/wiki/node-hosting

Thank you

Any questions?

find me at www.techjitsu.co.in

Made with Slides.com