NodeJs 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

Introduction to JavaScript

JavaScript is an object-based scripting language which is lightweight and


cross-platform.

JavaScript is not a compiled language, but it is a translated language. The


JavaScript Translator (embedded in the browser) is responsible for translating
the JavaScript code for the web browser.

JavaScript (js) is a light-weight object-oriented programming language which is


used by several websites for scripting the webpages. It is an interpreted, full-
fledged programming language that enables dynamic interactivity on
websites when applied to an HTML document. It was introduced in the year
1995 for adding programs to the webpages in the Netscape Navigator browser.
Since then, it has been adopted by all other graphical web browsers. With
JavaScript, users can build modern web applications to interact directly without
reloading the page every time. The traditional website uses js to provide several
forms of interactivity and simplicity.
Java Script Libraries
o JQuery
o React

Application of JavaScript

JavaScript is used to create interactive websites. It is mainly used for:

o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box,
confirm dialog box and prompt dialog box),

JavaScript Example
1. <script>  
2. document.write("Hello JavaScript by JavaScript");  
3. </script>  

Functions
A function is a block of code which will be executed only if it is called. If you
have a few lines of code that needs to be used several times, you can create a
function including the repeating lines of code and then call the function
wherever you want.

Types of Functions

There are two types of functions in JavaScript like other programming


languages such c, c++, and java etc.

o Pre-defined Functions
o User-defined Functions

Create a Function in JavaScript

1. Use the keyword function followed by the name of the function.


2. After the function name, open and close parentheses.
3. After parenthesis, open and close curly braces.
4. Within curly braces, write your lines of code.

Syntax:

function functionname()

lines of code to be executed

<html>
<head>
<title>Functions!!!</title>
<script type="text/javascript">
function myFunction()
{
document.write("This is a simple function.<br />");
}
myFunction();
</script>
</head>
<body>
</body>
</html

Function with Arguments


You can create functions with arguments as well. Arguments should be
specified within parenthesis

Syntax:

function functionname(arg1, arg2)

lines of code to be executed


}
Function Return

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute
the code after the invoking statement.

Functions often compute a return value. The return value is "returned" back to
the "caller":

Example

Calculate the product of two numbers, and return the result:

let x = myFunction(4, 3);   // Function is called, return value will end up in x

function myFunction(a, b) {
  return a * b;             // Function returns the product of a and b
}

Introduction to NodeJs
Node.js is a cross-platform runtime environment and library for running
JavaScript applications outside the browser. It is used for creating server-
side and networking web applications. It is open source and free to use.
Node.js is a platform built on Chrome's JavaScript runtime for easily
building fast and scalable network applications. Node.js uses an event-driven,
non-blocking I/O model that makes it lightweight and efficient, perfect for data-
intensive real-time applications that run across distributed devices

Features of Node.js

Following is a list of some important features of Node.js that makes it the first
choice of software architects.

1. Extremely fast: Node.js is built on Google Chrome's V8 JavaScript


Engine, so its library is very fast in code execution.
2. I/O is Asynchronous and Event Driven: All APIs of Node.js library
are asynchronous i.e. non-blocking. So, a Node.js based server never
waits for an API to return data. The server moves to the next API after
calling it and a notification mechanism of Events of Node.js helps the
server to get a response from the previous API call. It is also a reason that
it is very fast.
3. Single threaded: Node.js follows a single threaded model with event
looping.
4. Highly Scalable: Node.js is highly scalable because event mechanism
helps the server to respond in a non-blocking way.
5. No buffering: Node.js cuts down the overall processing time while
uploading audio and video files. Node.js applications never buffer any
data. These applications simply output the data in chunks.
6. Open source: Node.js has an open-source community which has
produced many excellent modules to add additional capabilities to
Node.js applications.

Application of NodeJS: NodeJS should be preferred to build:


 Real-Time Chats,
 Complex Single-Page applications,
 Real-time collaboration tools,
 Streaming apps
 JSON APIs based application
NPM - Node Package Manager

Node Package Manager (NPM) is a command line tool that installs, updates
or uninstalls Node.js packages in your application. It is also an online
repository for open-source Node.js packages. The node community around
the world creates useful modules and publishes them as packages in this
repository.

A package contains all the files needed for a module and modules are the
JavaScript libraries that can be included in Node project according to the
requirement of the project. NPM can install all the dependencies of a project
through the package. json file. It can also update and uninstall package

V8
V8 is a C++-based open-source JavaScript engine developed by Google. It
was originally designed for Google Chrome and Chromium-based browsers
(such as Brave) in 2008, but it was later utilized to create Node.js for server-
side coding. 
V8 is known to be a JavaScript engine because it takes JavaScript code and
executes it while browsing in Chrome. It provides a runtime environment for
the execution of JavaScript code. The best part is that the JavaScript engine is
completely independent of the browser in which it runs. This is the feature
that led Node.js designers to choose the V8 engine to power the framework, 

Asynchronous vs Synchronous request


1. Synchronous methods: Synchronous functions block the execution of
the program until the file operation is performed. These functions are
also called blocking functions. 
All asynchronous methods can perform synchronously just by appending “Sync” to
the function name. Some of the synchronous methods of fs module in NodeJS are:
 fs.readFileSync()
 fs.renameSync()
 fs.writeSync()
 fs.writeFileSync()
 fs.fsyncSync()
 fs.appendFileSync()
 fs.statSync()
 fs.readdirSync()
 fs.existsSync()
Example 1: Synchronous read method
Step 1: Let’s create a JavaScript file named main.js and a text file with the
name sample.txt having the following statement:
GeeksForGeeks is a Computer Science portal.
Step 2: Add the following code inside main.js file and execute it:
 main.js
var fs = require("fs");

// Synchronous read

console.log("Synchronous read method:");

var data = fs.readFileSync('sample.txt');

console.log("Data in the file is - " +


data.toString());

Output:

Asynchronous functions do not block the execution of the program and each
command is executed after the previous command even if the previous command has
not computed the result. The previous command runs in the background and loads
the result once it has finished processing. Thus, these functions are called non-
blocking functions. They take a callback function as the last parameter

Some of the asynchronous methods of fs module in NodeJS are:


 fs.readFile()
 fs.rename()
 fs.write()
 fs.writeFile()
 fs.fsync()
 fs.appendFile()
 fs.stat()
 fs.readdir()
 fs.exists()
Heavy operations which consume time for processing such as querying huge data
from a database should be done asynchronously as other operations can still be
executed and thus, reducing the time of execution of the program.
Example 1: Asynchronous read method
Step 1: Let’s create a JavaScript file named main.js and a text file with the
name sample.txt having the following statement: 
GeeksForGeeks is a Computer Science portal.
Step 2: Add the following code inside main.js file and execute it:
 main.js
var fs = require("fs");

// Asynchronous read

console.log("Asynchronous read method:");

fs.readFile('sample.txt', function (err, data) {

   if (err) {

      return console.error(err);

   }

   console.log("Data in the file is - " +


data.toString());

});

Output:
Difference between Asynchronous and Synchronous methods:
Sr.n
Synchronous methods Asynchronous methods
o

Synchronous functions are called blocking Asynchronous functions are called


1.
functions non-blocking functions.

It blocks the execution of the program


It does not block the execution of
2. until the file operation has finished
the program.
processing.

These functions take File Descriptor as the These functions take a callback
3.
last argument. function as the last argument.

Examples: fs.readFileSync(), Examples: fs.readFile(),


4. fs.appendFileSync(), fs.writeFileSync() fs.appendFile(), fs.writeFile(),
etc. fs.stat() etc.

REPL (READ, EVAL, PRINT, LOOP)

REPL (READ, EVAL, PRINT, LOOP) is a computer environment similar to


Shell (Unix/Linux) and command prompt. Node comes with the REPL
environment when it is installed. System interacts with the user through outputs of
commands/expressions used. It is useful in writing and debugging the codes. The
work of REPL can be understood from its full form:
Read : It reads the inputs from users and parses it into JavaScript data structure. It
is then stored to memory.
Eval : The parsed JavaScript data structure is evaluated for the results.
Print : The result is printed after the evaluation.
Loop : Loops the input command. To come out of NODE REPL, press ctrl+c twice
Getting Started with REPL:
To start working with REPL environment of NODE; open up the terminal (in case of
UNIX/LINUX) or the Command prompt (in case of Windows) and write node and
press ‘enter’ to start the REPL.

open node repl

The REPL has started and is demarcated by the ‘>’ symbol. Various operations can
be performed on the REPL. Below are some of the examples to get familiar with the
REPL environment.
Example: Performing Arithmetical operations in REPL

Arithmetical operations in REPL

Example: Performing operations using libraries of NODE. MATH library is being


used in below example.
Math library methods gfg

Note: using ‘math’ shows error as the library is referenced as ‘Math’ in NODE and


not ‘math’.
Example: Using variables in REPL. The keyword var is used to assign values to
variables.

Using Variables in REPL

Example: Using loops in REPL. Loops can be used in REPL as in other editors.


Note: Use ctrl – c to terminate the command and ctrl – c twice to terminate the
NODE REPL.
.help is used to list out all the commands.

Using .help in REPL

Working with Buffers and Streams

Streams

Streams are a fundamental concept in Node.js that provide a way to

process large amounts of data efficiently. Streams in Node.js are a type

of data handler that enable reading and writing data in chunks instead

of loading entire files into memory. This allows applications to process

data in a more efficient and scalable way.

In Node.js, there are four types of streams: Readable, Writable, Duplex,


and Transform. A Readable stream represents a source of data that can be
read from, while a Writable stream represents a destination for data that
can be written to. A Duplex stream represents both a Readable and
Writable stream, and a Transform stream represents a Duplex stream that
modifies or transforms the data as it passes through.

To use streams in Node.js, we can create a stream object using the


appropriate class from the ‘stream’ module, and then pipe the stream to
another stream or data source. For example, to read data from a file using a
Readable stream, we can use the ‘fs’ module to create a Readable stream
object, and then pipe it to a Writable stream that writes the data to the
console or another file.

Here’s an example of using streams in Node.js:

const fs = require('fs');

const readableStream = fs.createReadStream('input.txt');


const writableStream = fs.createWriteStream('output.txt');

readableStream.pipe(writableStream);

In this example, we create a Readable stream using the ‘fs’ module’s


‘createReadStream’ method, and a Writable stream using the
‘createWriteStream’ method. We then pipe the Readable stream to the
Writable stream using the ‘pipe’ method.

Buffer
Buffers are another important concept in Node.js that provide a way to
handle binary data in memory. Buffers are essentially arrays of integers that
represent raw binary data. They can be used to store data in memory, read
data from files or network sockets, and manipulate data in various ways.

In Node.js, Buffers are a built-in data type that are part of the ‘Buffer’
module. Buffers can be created in several ways, such as from a string, an
array, or a buffer from another source.

To create a Buffer in Node.js, we can use the ‘Buffer.from()’ method, which


takes a source data and an optional encoding parameter. For example, to
create a Buffer from a string, we can use the following code:

const buffer = Buffer.from('Hello, World!', 'utf-8');

Once we have a Buffer object, we can manipulate the data in various ways,
such as reading or writing individual bytes, copying data to another buffer,
or converting the buffer to a string.

Here’s an example of working with Buffers in Node.js:


const buffer1 = Buffer.from('Hello');
const buffer2 = Buffer.from('World');
const buffer3 = Buffer.concat([buffer1, buffer2]);

console.log(buffer3.toString());

In this example, we create two Buffer objects using the ‘Buffer.from()’


method, and then concatenate them into a third Buffer using the
‘Buffer.concat()’ method. We then convert the resulting buffer to a string
using the ‘toString()’ method and log it to the console.

Creating Server with Http request


To access web pages of any web application, you need a web server. The web
server will handle all the http requests for the web application e.g IIS is a web
server for ASP.NET web applications and Apache is a web server for PHP or Java
web applications.

Node.js provides capabilities to create your own web server which will handle
HTTP requests asynchronously. You can use IIS or Apache to run Node.js web
application but it is recommended to use Node.js web server.

Create Node.js Web Server


Node.js makes it easy to create a simple web server that processes incoming
requests asynchronously.

The following example is a simple Node.js web server contained in server.js file.

var http = require('http'); // 1 - Import Node.js core module

var server = http.createServer(function (req, res) { // 2 -


creating server

//handle incomming requests here..

});

server.listen(5000); //3 - listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')

In the above example, we import the http module using require() function. The
http module is a core module of Node.js, so no need to install it using NPM. The
next step is to call createServer() method of http and specify callback function
with request and response parameter. Finally, call listen() method of server
object which was returned from createServer() method with port number , to
start listening to incoming requests on port 5000. You can specify any unused port
here.

Run the above web server by writing node server.js command in command prompt


or terminal window and it will display message as shown below.

C:\> node server.js

Node.js web server at port 5000 is running..

This is how you create a Node.js web server using simple steps. Now, let's see how
to handle HTTP request and send response in Node.js web server.
442.5K

Streaming service limits videos to just 10 minutes

Handle HTTP Request


The http.createServer() method includes request and response parameters which is
supplied by Node.js. The request object can be used to get information about the
current HTTP request e.g., url, request header, and data. The response object can be
used to send a response for a current HTTP request.

The following example demonstrates handling HTTP request and response in


Node.js.

var http = require('http'); // Import Node.js core module

var server = http.createServer(function (req, res) { //create web


server
if (req.url == '/') { //check the URL of the current request

// set response header


res.writeHead(200, { 'Content-Type': 'text/html' });

// set response content


res.write('<html><body><p>This is home
Page.</p></body></html>');
res.end();

}
else if (req.url == "/student") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is student
Page.</p></body></html>');
res.end();

}
else if (req.url == "/admin") {

res.writeHead(200, { 'Content-Type': 'text/html' });


res.write('<html><body><p>This is admin
Page.</p></body></html>');
res.end();

}
else
res.end('Invalid Request!');

});

server.listen(5000); //6 - listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')

In the above example, req.url is used to check the url of the current request and
based on that it sends the response. To send a response, first it sets the response
header using writeHead() method and then writes a string as a response body
using write() method. Finally, Node.js web server sends the response using end()
method.

Now, run the above web server as shown below.

C:\> node server.js

Node.js web server at port 5000 is running..

To test it, you can use the command-line program curl, which most Mac and Linux
machines have pre-installed.

curl -i http://localhost:5000

You should see the following response.


HTTP/1.1 200 OK

Content-Type: text/plain

Date: Tue, 8 Sep 2015 03:05:08 GMT

Connection: keep-alive

This is home page.

For Windows users, point your browser to http://localhost:5000 and see the


following result.

Events
Every action on a computer is an event. Like when a connection is made or a
file is opened.

Node.js EventEmitter
Node.js allows us to create and handle custom events easily by using events
module. Event module includes EventEmitter class which can be used to raise and
handle custom events.

The following example demonstrates EventEmitter class for raising and handling a
custom event.
Example: Raise and Handle Node.js events

 Copy
// get the reference of EventEmitter class of events module
var events = require('events');

//create an object of EventEmitter class by using above reference


var em = new events.EventEmitter();

//Subscribe for FirstEvent


em.on('FirstEvent', function (data) {
console.log('First subscriber: ' + data);
});

// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter
example.');

In the above example, we first import the 'events' module and then create an object
of EventEmitter class. We then specify event handler function using on() function.
The on() method requires name of the event to handle and callback function which
is called when an event is raised.

Process
The process module in Node.js allows us to get information related to the
node and control its behavior. This module is, and we can use it to get
information such as process ID, version, release, CPU usage, and uptime
globally available or perform actions such as killing processes, setting uid,
setting groups, unmasking, etc.

example 1

// Including the module into out project

var process = require('process');

  

// Viewing the current working directory

console.log('Working directory --> ' + process.cwd());

  

// Viewing the version of process we are using
console.log('Process version --> ' + process.version);

  

// Viewing the type of OS we are using

console.log('Current OS --> ' + process.platform);

// Viewing the arguments passed

console.log('Arguments --> ', process.argv);

// Viewing the Feature Object

console.log('Feature Property: \n', process.features);

 Line 2: We include the process module in our code.


 Line 5: We print the current working directory using process.
 Line 8: We print the version of process that we are using.
 Line 11: We print the type of OS we are working on.
 Line 14: We print the arguments passed when the current application was run.
 Line 17: We view the Feature Object in process.

You might also like