0% found this document useful (0 votes)
24 views15 pages

Js Notes

The document discusses various types of timers in Node.js - timeout, interval, and immediate. It provides examples of using setTimeout() and clearTimeout() to run code after a delay or to cancel a timeout. It also discusses using setInterval() and clearInterval() to run code repeatedly at an interval and stop the repetition. The document explains how to create and handle custom events using the EventEmitter class and the events module. It also discusses promises, including creating custom promises, chaining promises, and handling errors with promises. Finally, it covers using await expressions with async functions to wait for promises to resolve.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views15 pages

Js Notes

The document discusses various types of timers in Node.js - timeout, interval, and immediate. It provides examples of using setTimeout() and clearTimeout() to run code after a delay or to cancel a timeout. It also discusses using setInterval() and clearInterval() to run code repeatedly at an interval and stop the repetition. The document explains how to create and handle custom events using the EventEmitter class and the events module. It also discusses promises, including creating custom promises, chaining promises, and handling errors with promises. Finally, it covers using await expressions with async functions to wait for promises to resolve.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

types of timers you can implement in Node.

js:

 timeout,
 interval,
 immediate.

a) timeout timers:- Timeout timers are used to delay work for a specific amount
of time. When that time expires, the callback function is executed and the timer
goes away. Use timeouts for work that only needs to be performed once.

The Node.js setTimeout function is built in the Node.js function that runs the
specified program after a certain period of time passes. This time is always defined
in milliseconds. setTimeout() accepts a callback function as the first argument
and the delay time as the second. If the delay argument is omitted, it defaults
to 0.

Syntax of Node.js setTimeout()

1. Without Arguments

// Define the callback function

function callbackFunction() {

// Code here

setTimeout(callbackFunction, delayTimeInMS)

2. With Optional Arguments

// Define the callback function

function callbackFunction(arg) { // Code here}

setTimeout(callbackFunction, delayTimeInMS, “passArgHere”)

Different Examples using Node.JssetTimeout


Example-1: Print “Hello world” after 3 seconds
function greet() {
console.log(“Hello world”)
}
setTimeout(greet, 3000)
console.log(“Print first”)
output:-
Print first
Hello world
Example-2: Using an Argument
function greet(name) {
console.log("Hello"+ name)
}
// pass argument
setTimeout(greet, 3000, “Jane”)
console.log(“Print first”)
output:-
Print first
Hello Jane

Example-3: Using Multiple Arguments

function greet(fname,lname) {

console.log('Hello'+fname+lname);}

setTimeout(greet, 3000, "Jane", "Doe")

console.log("Print first")

clearTimeout:-The setTimeout() function returns a timer object ID. You can pass
this ID to clearTimeout(timeoutId) at any time before the delayMilliSeconds
expires to cancel the timeout function. For example:

myTimeout = setTimeout(myFunc, 100000);

clearTimeout(myTimeout);
Example:-simple_timer.js:

Implementing a series of timeouts at various intervals

function simpleTimeout(consoleTimer){

console.timeEnd(consoleTimer); //end the timer

setTimeout(simpleTimeout, 2000, "twoSecond");


console.time("oneSecond");
setTimeout(simpleTimeout, 1000, "oneSecond");
console.time("fiveSecond");
setTimeout(simpleTimeout, 5000, "fiveSecond");
console.time("50MilliSecond");
setTimeout(simpleTimeout, 50, "50MilliSecond");
output:-
50MilliSecond: 50.489ms
oneSecond: 1000.688ms
twoSecond: 2000.665ms
fiveSecond: 5000.186ms

 setInterval:- allows us to run a function repeatedly, starting after the interval of


time, then repeating continuously at that interval.To stop further calls, we should
call clearInterval(timerId).
 The setInterval() function returns a timer object ID. You can pass this ID to
clearInterval(intervalId) at any time before the delayMilliSeconds expires to cancel
 the timeout function. For example:
 myInterval = setInterval(myFunc, 100000);
 …
 clearInterval(myInterval);
The following example will show the message every 2 seconds. After 5 seconds,
the output is stopped:
Example:-
var x=0, y=0, z=0;
function displayValues()
{
console.log(“X=%d; Y=%d; Z=%d”, x, y, z);
}
function updateX()
{
x+=1; }
function updateY()
{
y+=1; }
function updateZ()
{
z+=1;
displayValues(); }
setInterval(updateX, 500);
setInterval(updateY, 1000);
setInterval(updateZ, 2000);
output:-
x=3; y=1; z=1
x=7; y=3; z=2
x=11; y=5; z=3
x=15; y=7; z=4
x=19; y=9; z=5
x=23; y=11; z=6

Node.js EventEmitter:- Node.js uses events module to create and handle custom
events. The EventEmitter class can be used to create and handle custom events
module.
The syntax to Import the events module are given below:
Syntax:
Const EventEmitter = require('events');
All EventEmitters emit the event newListener when new listeners are added
and removeListener when existing listeners are removed.
Listening events:- Before emits any event, it must register functions(callbacks) to
listen to the events.
Syntax:
eventEmitter.addListener(event, listener)
or
eventEmitter.on(event, listener)
eventEmitter.on(event,listener) and eventEmitter.addListener(event,listener) a
re pretty much similar. It adds the listener at the end of the listener’s array for the
specified event. Multiple calls to the same event and listener will add the listener
multiple times and correspondingly fire multiple times. Both functions return
emitter, so calls can be chained.
Emitting events: Every event is named event in nodejs. We can trigger an event
by emit(event, [arg1], [arg2], […]) function. We can pass an arbitrary set of
arguments to the listener functions.
Syntax:
eventEmitter.emit(event, [arg1], [arg2], [...])
Example:-
// Importing events
Const EventEmitter = require('events');
// Initializing eventemitter instances
Var e = new EventEmitter();
// Registering to myEvent
e.on('myEvent', (msg) => { console.log(msg);});
// Triggering myEvent
e.emit('myEvent', "First event");
Output:-
First event
Removing Listener: The eventEmitter.removeListener() takes two argument
event and listener, and removes that listener from the listeners array that is
subscribed to that event. While eventEmitter.removeAllListeners() removes all
the listener from the array which are subscribed to the mentioned event.
Syntax:
eventEmitter.removeListener(event, listener)
eventEmitter.removeAllListeners([event])

What is a promise?

A promise is essentially an improvement of callbacks that manage all


asynchronous data activities. A JavaScript promise represents an activity that will
either be completed or declined. If the promise is fulfilled, it is resolved; otherwise,
it is rejected. Promises, unlike typical callbacks, may be chained.

JavaScript promises have three states: pending, resolved, and rejected.

const isLessThan10 = (num) => {

new Promise((resolve, reject) => {

if (num < 10) {

resolve("Correct");

} else {

reject("Wrong!!");

})

.then((res) => console.log(res))

.catch((err) => console.log(err));

};

isLessThan10(14);

The pending state is the initial state that occurs when a promise is called. While a
promise is pending, the calling function continues to run until the promise is
completed, returning whatever data was requested to the calling function.

When a promise is completed, it ends in either the resolved state or the rejected
state. The resolved state indicates that the promise was successful and that the
desired data is passed to the .then() method.

The rejected state indicates that a promise was denied, and the error is passed to
the .catch() method.
Creating a custom promise
function getSumNum(a, b) {

const customPromise = new Promise((resolve, reject) => {

const sum = a + b;

if(sum <= 5){

resolve("Let's go!!")

} else {

reject(new Error('Oops!.. Number must be less than 5'))

})

return customPromise

Chaining promises
Promises can be used to execute a series of asynchronous tasks in sequential
order. Chaining multiple then() Promise outcome helps avoid the need to code
complicated nested functions (which can result in callback hell).

To demonstrate chaining promises, let’s utilize the previous code with a few
modifications:

let value;

function getSumNum(a, b) {
const customPromise = new Promise((resolve, reject) => {
const sum = a + b;

if(sum < 5){


resolve(sum)
} else {
reject(new Error('Oops!.. Number must be less than 5'))
}
})

return customPromise
}

getSumNum(1, 3)
.then(data => {
console.log("initial data: " + data)
value = data + 1 // modifying the returned data

return value
})
.then(newData => {
console.log("modified data: " + newData)
})
.catch(err => {
console.log(err)
})

Promises and Errors

fetch("/api/user/profile") // Start the HTTP request

.then(response => { // Call this when status and headers are ready

if (!response.ok) { // If we got a 404 Not Found or similar error

return null; // Maybe user is logged out; return null profile

// Now check the headers to ensure that the server sent us JSON.

// If not, our server is broken, and this is a serious error!

let type = response.headers.get("content-type");

if (type !== "application/json") {


throw new TypeError(`Expected JSON, got ${type}`);

// If we get here, then we got a 2xx status and a JSON content-type

// so we can confidently return a Promise for the response

// body as a JSON object.

return response.json();

})

.then(profile => { // Called with the parsed response body or null

if (profile) {

displayUserProfile(profile);

else { // If we got a 404 error above and returned null we end up here

displayLoggedOutProfilePage();

})

.catch(e => {

if (e instanceof NetworkError) {

// fetch() can fail this way if the internet connection is down

displayErrorMessage("Check your internet connection.");

else if (e instanceof TypeError) {

// This happens if we throw TypeError above

displayErrorMessage("Something is wrong with our server!");


}

else {

// This must be some kind of unanticipated error

console.error(e);

});

await Expressions

The await keyword takes a Promise and turns it back into a return value or a
thrown exception. Given a Promise object p, the expression await p waits until p
settles. If p fulfills, then the value of await p is the fulfillment value of p. On the
other hand, if p is rejected, then the await p expression throws the rejection value
of p.

async Functions

Because any code that uses await is asynchronous, there is one critical rule: you
can only use the await keyword within functions that have been declared with the
async keyword.

Example:-

async function getHighScore() {

let response = await fetch("/api/user/profile");

let profile = await response.json();

return profile.highScore;

Declaring a function async means that the return value of the function will be a

Promise even if no Promise-related code appears in the body of the function. If an


async function appears to return normally, then the Promise object that is the real

return value of the function will resolve to that apparent return value. And if an

async function appears to throw an exception, then the Promise object that it
returns will be rejected with that exception.

The getHighScore() function is declared async, so it returns a Promise. And


because it returns a Promise, we can use the await keyword with it:

displayHighScore(await getHighScore());

(OR)

getHighScore().then(displayHighScore).catch(console.error);

Awaiting Multiple Promises

Suppose that we’ve written our getJSON() function using async:

async function getJSON(url) {

let response = await fetch(url);

let body = await response.json();

return body;

And now suppose that we want to fetch two JSON values with this function:

let value1 = await getJSON(url1);

let value2 = await getJSON(url2);

In order to await a set of concurrently executing async functions, we use


Promise.all() just as we would if working with Promises directly:

let [value1, value2] = await Promise.all([getJSON(url1), getJSON(url2)]);


Implementation Details:
function f(x) {
return new Promise(function(resolve, reject) {
try {
resolve((function(x) { /* body */ })(x));
}
catch(e) {
reject(e);
}
});
}
Command line arguments:-
Exmple:-Program to add two numbers passed as arguments.

Step 1: Save the file as index1.js and paste the below code inside the file.

var arguments = process.argv

function add(a, b) {

return parseInt(a)+parseInt(b)

var sum = add(arguments[2], arguments[3])

console.log("Addition of 2, 3 is ", sum)

Step 2: Run index1.js file using below command:

node index1.js 2 3
Node is Asynchronous by Default

The util.promisify() method defines in utilities module of Node.js standard library.


It is basically used to convert a method that returns responses using a callback
function to return responses in a promise object.

Example:-

// Importing Utilities module

const util = require('util')

// Importing File System module

const fs = require('fs')

// Use promisify to convert callback

// based method fs.readdir to

// promise based method

const readdir = util.promisify(fs.readdir)

readdir('process.cwd()')

.then(files => {

console.log(files)

})

.catch(err => {

console.log(err)

})

Streams:-

Implementing a Readable Stream: We will read the data from inStream and
echoing it to the standard output using process.stdout.
Example:-

// Sample JavaScript Code for creating

// a Readable Stream

// Accessing streams

const { Readable } = require('stream');

// Reading the data

const inStream = new Readable({

read() { }

});

// Pushing the data to the stream

inStream.push('GeeksForGeeks : ');

inStream.push( 'A Computer Science portal for Geeks');

// Indicates that no more data is

// left in the stream

inStream.push(null);

// Echoing data to the standard output

inStream.pipe(process.stdout);

Output:

GeeksForGeeks : A Computer Science portal for Geeks

Pipe:-

The readable.pipe() method in a Readable Stream is used to attach a Writable


stream to the readable stream so that it consequently switches into flowing mode
and then pushes all the data that it has to the attached Writable.
Syntax:

readable.pipe( destination, options )

Parameters: This method accept two parameters as mentioned above and described
below:

destination: This parameter holds the destination of writing data.

options: This parameter holds the pipe options.

Example:-

// Node.js program to demonstrate the

// readable.pipe() method

// Accessing fs module

var fs = require("fs");

// Create a readable stream

var readable = fs.createReadStream('input.txt');

// Create a writable stream

var writable = fs.createWriteStream('output.txt');

// Calling pipe method

readable.pipe(writable);

console.log("Program Ended");

You might also like