Review Webserversss

You might also like

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

Introduction to Node.

JS
What is Node.js
It is a runtime environment for JavaScript that runs on the server.  It is open source,
cross-platform, and since its introduction in 2009, it got hugely popular and now
plays a significant role in the web development scene.
 

It runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser.
Node.js is able to leverage the work of the engineers that made (and will continue to
make) the Chrome JavaScript runtime blazing fast, and this allows Node.js to benefit
from the huge performance improvements and the Just-In-Time compilation that V8
performs.

A Node.js app is run by a single process, without creating a new thread for every


request. Node provides a set of asynchronous I/O primitives in its standard library
that will prevent JavaScript code from blocking and generally, libraries in Node.js are
written using non-blocking paradigms, making a blocking behavior an exception
rather than the normal.

 
In Node.js, the new ECMAScript standards can be used without problems, as you
don’t have to wait for all your users to update their browsers - you are in charge of
deciding which ECMAScript version to use by changing the Node.js version, and you
can also enable specific experimental features by running Node with flags.

                                                                                                                                          
History of Node.js
 JavaScript is a programming language that was created at Netscape as a
scripting tool to manipulate web pages inside their browser, Netscape
Navigator.
 Part of the business model of Netscape was to sell Web Servers, which
included an environment called Netscape LiveWire that could create
dynamic pages using server-side JavaScript. Unfortunately, Netscape
LiveWire wasn't very successful and server-side JavaScript wasn't
popularized until recently, by the introduction of Node.js.
 One key factor that led to the rise of Node.js was the timing. Just a few
years earlier, JavaScript had started to be considered as a more serious
language, thanks to "Web 2.0" applications (such as Flickr, Gmail, etc.) that
showed the world what a modern experience on the web could be like.
 JavaScript engines also became considerably better as many browsers
competed to offer users the best performance. Development teams behind
major browsers worked hard to offer better support for JavaScript and find
ways to make JavaScript run faster. The engine that Node.js uses under the
hood, V8 (also known as Chrome V8 for being the open-source JavaScript
engine of The Chromium Project), improved significantly due to this
competition.
 Node.js was written and introduced by Ryan Dahl in 2009

Year Improvements

 Node.js is born
2009  The first form of npm is created

 Express is born
2010  Socket.io is born

 npm hits version 1.0


 Larger companies start adopting Node.js: LinkedIn, Uber, etc.
2011
 hapi is born

 Adoption continues very rapidly.


2012

 First big blogging platform using Node.js: Ghost


2013  Koa is born
 The Big Fork: io.js is a major fork of Node.js, with the goal of introducing
2014 ES6 support and moving faster

 The Node.js Foundation is born


 IO.js is merged back into Node.js
2015  npm introduces private modules
 Node.js 4 (versions 1, 2 and 3 never previously released)

 The leftpad incident
 Yarn is born
2016
 Node.js 6

 npm focuses more on security


 Node.js 8
 HTTP/2
2017  V8 introduces Node.js in its testing suite, officially making Node.js a target
for the JS engine, in addition to Chrome
 3 billion npm downloads every week

 Node.js 10
2018  ES modules .mjs experimental support

Different Features of Node.js


 It’s easy to get started and can be used for prototyping and agile
development
 It provides fast and highly scalable services
 It uses JavaScript everywhere so it’s easy for a JavaScript programmer to
build back-end services using Node.js
 Source code are cleaner and consistent.
 Large ecosystem for open source library.
 It has Asynchronous or Non-blocking nature.
Advantages of Using Node.js
 Easy Scalability - Developers prefer to use Node.js because it is easily
scaled the application in both horizontal and vertical direction. We can also
add extra resources during the scalability of application.
 Real-time Web Apps - If you are building a web app you can also use PHP
and it will take the same amount of time when you use Node.js, But if I am
talking about building chat apps or gaming apps Node.js is much more
preferable because of faster synchronization. Also, event loop avoids HTTP
overload for Node.js development.
 Fast Suite - js runs on the V8 engine developed by Google. Event loop in
Node.js handles all asynchronous operation so Node.js acts like a fast suite
and all the operations can be done quickly like reading or writing in the
database, network connection or file system
 Easy to learn and code – js is easy to learn and code because it uses
JavaScript. If you are a front-end developer and have a good grasp on
JavaScript you can easily learn and build the application on Node.js
 Advantage of Caching - It provides the caching of single module.
Whenever there is any request for the first module, it gets cached in the
application memory so you don’t need to re-execute the code.
 Data Streaming - In Node.js HTTP request and response are considered as
two separate events. They are data stream so when you process a file at
the time of loading it will reduce the overall time and will make it faster
when the data is presented in the form of transmissions. It also allows you
to stream audio and video files at lightning speed.
 Hosting - PaaS (Platform as a Service) and Heroku are the hosting platform
for NodeJS application deployment which is easy to use without facing any
issue.
 Corporate Support - Most of the well-known companies like Wallmart,
Paypal, Mirosoft, yahoo are using Node.js for building the applications.
Node.js uses JavaScript so most of the companies are combining front-end
and backend Teams together into a single unit.

Application of Node.js
 Real Time Chats,
 Complex Single-Page applications,
 Real-time collaboration tools,
 Streaming apps

Also, JSON APIs based application.

Setting-Up the Environment


Background
 The node.js development environment can be setup in Windows, Mac,
Linux and Solaris. The following tools/SDK are required for developing a
Node.js application on any platform.
 js
o js can be installed in different ways. Official packages for all the
major platforms are available at
https://nodejs.org/en/download/
o One very convenient way to install Node.js is through a package
manager. In this case, every operating system has its own.
 Node Package Manager (NPM) - is included in Node.js installation since
Node version 0.6.0., so there is no need to install it separately.
 IDE (Integrated Development Environment) or TextEditor

Install Node.js on Windows



o Visit Node.js official web site https://nodejs.org. It will
automatically detect OS and display download link as per your
Operating System. For example, it will display following
download link for 64 bit Windows OS.
o Download node MSI for windows by clicking on 8.11.3 LTS or
10.5.0 Current button. We have used the latest version 10.5.0
for windows throughout these tutorials.
 After you download the MSI, double-click on it to start the installation as
shown below.
 Click Next to read and accept the License Agreement and then click Install.
It will install Node.js quickly on your computer.
 Finally, click finish to complete the installation.

 To verify the installation, open the command prompt and type node –v. If
Node.js is installed successfully then it will display the version of the
Node.js installed on your machine as shown on the right.

Install Node.js on Mac/Linux



o Visit Node.js official website https://nodejs.org/en/download
o Click on the appropriate installer for Mac (.pkg or .tar.gz) or
Linux to download the Node.js installer.
o Once downloaded, click on the installer to start the Node.js
installation wizard. Click on Continue and follow the steps.
o After successful installation, it will display summary of
installation about the location where it installed Node.js and
NPM.
o After installation, verify the Node.js installation using terminal
window and enter the following command. It will display the
version number of Node.js installed on your Mac.
o Optionally, for Mac or Linux users, you can directly install
Node.js from the command line using Homebrew package
manager for Mac OS or Linuxbrew package manager for Linux
Operating System. For Linux, you will need to install additional
dependencies, viz. Ruby version 1.8.6 or higher and GCC version
4.2 or higher before installing node.

 IDE (Integrated Development Environment)


o js application uses JavaScript to develop an application. So, you
can use any IDE or texteditor tool that supports JavaScript
syntax. However, an IDE that supports auto complete features
for Node.js API is recommended e.g. Visual Studio, Sublime text,
Eclipse, Aptana etc.
 js Console – REPL
o js comes with virtual environment called REPL (aka Node shell).
REPL stands for Read-Eval-Print-Loop. It is a quick and easy
way to test simple Node.js/JavaScript code.
o To launch the REPL (Node shell), open command prompt (in
Windows) or terminal (in Mac or UNIX/Linux) and type nodeas
shown below. It will change the prompt to > in Windows and
MAC.
o You can now test pretty much any Node.js/JavaScript
expression in REPL. For example, if your write "10 + 20" then it
will display result 30 immediately in new line.

 The + operator also concatenates strings as in browser's JavaScript


 You can also define variables and perform some operation on them.
 If you need to write multi line JavaScript expression or function then just
press Enter whenever you want to write something in the next line as a
continuation of your code. The REPL terminal will display three dots (...), it
means you can continue on next line. Write .break to get out of continuity
mode.
 For example, you can define a function and execute it as shown below.

 You can execute an external JavaScript file by writing node filename  For


example, assume that node-example.js is on C drive of your PC with
following code.

 Now, you can execute node-example.js from command prompt as shown


                                    

 To exit from the REPL terminal, press Ctrl + C twice or write .exit and press
Enter.
 Thus, you can execute any Node.js/JavaScript code in the node shell
(REPL). This will give you a result which is similar to the one you will get in
the console of Google Chrome browser.

 The following table lists important REPL commands:

REPL COMMAND DESCRIPTION

.help Display help on all the commands

tab Keys Display the list of all commands.

Up/Down Keys See previous commands applied in REPL.

.save filename Save current Node REPL session to a file.

Load the specified file in the current Node


.load filename
REPL session.

Ctrl + C Terminate the current command.

Ctrl + C (twice) Exit from the REPL.

Ctrl + D Exit from the REPL.

.break Exit from multiline expression.

.clear Exit from multiline expression.


Basics of Node.JS
Node.js supports JavaScript. So, JavaScript syntax on Node.js is similar to the
browser's JavaScript syntax.

 Primitive Types: String, Number, Boolean, Undefined, Null and RegExp


 Everything else is an object in Node.js
 Loose Typing
o JavaScript in Node.js supports loose typing like the browser's
JavaScript.
o Use var keyword to declare a variable of any type.
 Object Literal
o Object literal syntax is same as browser's JavaScript.

Functions

o Functions are first class citizens in Node's JavaScript, similar to
the browser's JavaScript. A function can have attributes and
properties also. It can be treated like a class in JavaScript.
 
Defaults to Local

o Node's JavaScript is different from browser's JavaScript when it
comes to global scope. In the browser's JavaScript, variables
declared without var keyword become global. In Node.js,
everything becomes local by default.

Access Global Scope



o In a browser, global scope is the window object. In
Node.js, global object represents the global scope.
o To add something in global scope, you need to export it using
export or module.export. The same way, import modules/object
using require() function to access it from the global scope.
o For example, to export an object in Node.js, use exports.name =
object. See image below.

                                                                                                                          
Now, you can import log object using require() function and use it anywhere in your
Node.js project.
 Node Modules
o Module in Node.js is a simple or complex functionality organized
in single or multiple JavaScript files which can be reused
throughout the Node.js application.
o Each module in Node.js has its own context, so it cannot
interfere with other modules or pollute global scope. Also, each
module can be placed in a separate .js file under a separate
folder.
o js implements CommonJS modules standard. CommonJS is a
group of volunteers who define JavaScript standards for web
server, desktop, and console application.
o js Module Types:
 js Core Modules - Node.js is a light weight framework.
The core modules include bare minimum
functionalities of Node.js. These core modules are
compiled into its binary distribution and load
automatically when Node.js process starts. However,
you need to import the core module first in order to
use it in your application.
 The following table lists some of the important core
modules in Node.js.

Core Module Description

http module includes classes, methods


http and events to create Node.js http
server.

url module includes methods for URL


url
resolution and parsing.

querystring module includes methods


querystring
to deal with query string.

path module includes methods to deal


path
with file paths.

fs module includes classes, methods,


fs
and events to work with file I/O.

util module includes utility functions


util
useful for programmers.
 In order to use Node.js core or NPM modules, you first need to import it
using require() function as shown below.
o var module = require(‘module name’)
o As per above syntax, specify the module name in the require()
function. The require() function will return an object, function,
property or any other JavaScript type, depending on what the
specified module returns.
 Loading Core Modules


o In the above example, require() function returns an object
because http module returns its functionality as an object, you
can then use its properties and methods using dot notation
e.g. createServer().
o In this way, you can load and use Node.js core modules in your
application.

We will be using core modules throughout this lesson.

Writing a Simple Module


Writing a simple logging module which logs the information, warning or error to the
console.
In Node.js, module should be placed in a separate JavaScript file. So, create a Log.js
file and write the following code in it.
In the example shown above, the logging module created an object with three
functions - info(), warning() and error().  At the end, the functions have been assigned 
to exports. The module.exports in the example exposes a log object as a module.

 The exports  is a special object which is included in every JS file in the


Node.js application by default.
 Use module.exports or exports to expose a function, object or variable as a
module in Node.js.

Loading Local Module


To use local modules within an application, it needs to be loaded using require()
function in the same way as core module. However, it needs to be specified on the
path of JavaScript file within the module.
The following example demonstrates how to use the above logging module contained
in  Log.js.

o
 In the example, app.js is using log module. First, it
loads the logging module using require() function and
specified path where logging module is stored.
Logging module is contained in Log.js file in the root
folder. So, we have specified the path './Log.js' in the
require() function. The '.' denotes a root folder.
 The require() function returns a log object because
logging module exposes an object in Log.js using
module.exports. So now you can use logging module
as an object and call any of its function using dot
notation e.g myLogModule.info() or
myLogModule.warning() or myLogModule.error()
 Run the above example using command prompt (in
Windows) as shown below.


o
 A local module can be created using module.exports,
which can be used in an application.
 Local modules are modules created locally in your
Node.js application. These modules include different
functionalities of your application in separate files and
folders. You can also package it and distribute it via
NPM, so that Node.js community can use it.
 For example, if you need to connect to MongoDB and
fetch data then you can create a module for it, which
can be reused in your application.
Export Modules in Node.js
The module.exports or exports is a special object which is included in every JS file in
the Node.js application by default. module is a variable that represents current
module and exports is an object that will be exposed as a module. So, whatever you
assign to module.exports or exports, will be exposed as a module. Let's see how to
expose different types as a module using module.exports.

 Export Literals
o As mentioned above, exports is an object. So it exposes
whatever you assigned to it as a module. For example, if you
assign a string literal then it will expose that string literal as a
module.
o The following example exposes simple string message as a
module in Message.js.


o Now, import this message module and use it as shown below.


o Run the above example and see the result as shown below.

o Note: You must specify './' as a path of root folder to import a local
module. However, you do not need to specify path to import Node.js
core module or NPM module in the require() function.

Export Object
exports is an object. So, you can attach properties or methods to it. The following
example exposes an object with a string property in Message.js file.

In the above example, we have attached a property "SimpleMessage" to the exports


object. Now, import and use this module as shown below.

In the above example, require() function will return an object { SimpleMessage : 'Hello


World’} and assign it to the msg variable. So, now you can use msg.SimpleMessage.
Run the above example by writing node app.js in the command prompt and see the
output as shown below.
The same way as above, you can expose an object with function.  The following example
exposes an object with log function as a module.

The above module will expose an object- { log : function(msg) { console.log(msg); } }.


Run and see the output in command prompt as shown below.
You can also attach an object to module.exports as shown below.

Run the above example and see the result as shown on the next slide.

Export Functions
You can attach an anonymous function to exports object as shown below.

Now, you can use the above module (log.js) as below.


The msg variable becomes function expression in the above example. So, you can
invoke the function using parenthesis (). Run the above example and see the output
as shown below.

Export Function as Class


In the JavaScript, a function can be treated like a class. The following example
exposes a function which can be used like a class.

The previous module (person.js) can be used as shown below.


As you can see, we have created a person object using new keyword. Run the above
example as below.

In this way, you can export and import a local module created in a separate file under
root folder.
Node.js also allows you to create modules in sub folders. Let's see how to load
module from sub folders.

Load Module from Separate Folder


Use the full path of a module file where you have exported it using module.exports.
For example, if log module in the log.js is stored under "utility" folder under the root
folder of your application then import it as shown below.

 
In the example below, Node will search for a package definition file called
package.json inside utility folder. This is because Node assumes that this folder is a
package and will try to look for a package definition. The package.json file should be
in a module directory. The package.json under utility folder specifies the file name
using "main" key as below.

Now, Node.js will find log.js file using main entry in package.json and import it.

The 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.
 Official website: https://www.npmjs.com
 NPM is included with Node.js installation. After you install Node.js, verify
NPM installation by writing the following command in terminal or
command prompt.
 If you have an older version of NPM then you can update it to the latest
version using the following command.

 To access NPM help, write npm helpin the command prompt or terminal


window.

 NPM performs the operation in two modes: global and local. In the global
mode, NPM performs operations which affect all the Node.js applications
on the computer whereas in the local mode, NPM performs operations for
the particular local directory which affects an application in that directory
only.
 Install Package Locally
o Use the following command to install any third party module in
your local Node.js project folder.

 

o For example, the following command will install ExpressJS into
MyNodeProj folder.


o All the modules installed using NPM are installed
under node_modules The above command will create ExpressJS
folder under node_modules folder in the root folder of your
project and install Express.js there.

 Add Dependency into package.json


o Use --save at the end of the install command to add dependency
entry into package.json of your application.


o For example, the following command will install ExpressJS in
your application and also adds dependency entry into the
package.json.

 

o NPM can also install packages globally so that all the node.js
application on that computer can import and use the installed
packages. NPM installs global packages
into /<User>/local/lib/node_modules
o Apply -g in the install command to install package globally. For
example, the following command will install ExpressJS globally.

 Update Package
o To update the package installed locally in your Node.js project,
navigate the command prompt or terminal window path to the
project folder and write the following update command.


o The following command will update the existing ExpressJS
module to the latest version.

 Uninstall Packages
o Use the following command to remove a local package from
your project.


o The following command will uninstall ExpressJS from the
application.

Node.js as a 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.

In the above example, the http module was imported using require().  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 number.
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.

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

Handle HTTP Request



o The 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.
o The following example demonstrates handling HTTP request and
response in Node.js.

 
In the provided code above, 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.

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

You should see the following response:

For Windows users, point your browser to http://localhost:5000  (Links to an external


site.) and see the following result.

 
The same way, point your browser to http://localhost:5000/studentand see the
following result.
It will display "Invalid Request" for all requests other than the above URLs.
The following example demonstrates how to serve JSON response from the Node.js
web server.

You might also like