Complete Nodejs Developer: Graphic Era Hill University, Dehradun
Complete Nodejs Developer: Graphic Era Hill University, Dehradun
Complete Nodejs Developer: Graphic Era Hill University, Dehradun
MOOCS REPORT
SUBMITTED BY
Suraj Pathak
4. E-mail: surajpathak704@gmail.com
5. Mobile No:8006022381
7. SEC-C
8. Batch: 2020-2022
Introduction
I am Suraj Pathak, I have Enrolled in 5 weeks Online Course. Which has been
What is Node JS: -
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code
outside a browser. You need to remember that NodeJS is not a framework and it’s not a
programming language. Most people are confused and understand it’s a framework or a
programming language. We often use Node.js for building back-end services like APIs like Web
App or Mobile App. It’s used in production by large companies such as Paypal, Uber, Netflix,
Walmart, and so on.
Node.js gave rise to the Full Stack Developers who are now able to manage server and
client side by their own. Node.js is fast and reliable for heavy files and heavy network load
applications due to its event driven, non-blocking, and asynchronous approaches, where
developers
can also maintain a complete projects in single pages (SPA) and can use for IOT.
Features of NodeJS:-
There are other programming languages also which we can use to build back-end services so what
makes Node.js different I am going to explain.
1. It’s easy to get started and can be used for prototyping and agile development
2. It provides fast and highly scalable services
3. It uses JavaScript everywhere, so it’s easy for a JavaScript programmer to build back-end
services using Node.js
4. Source code cleaner and consistent.
5. Large ecosystem for open source library.
6. It has Asynchronous or Non-blocking nature
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
Advantages of NodeJS:-
Here are the benefits of using Node.js
1. Easy Scalability: Developers prefer to use Node.js because it is easily scaling the
application in both horizontal and vertical directions. We can also add extra resources during
the scalability of the application.
2. 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, the
event loop avoids HTTP overloaded for Node.js development.
3. Fast Suite: NodeJs runs on the V8 engine developed by Google. Event loop in NodeJs
handles all asynchronous operation so NodeJs 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
4. Easy to learn and code: NodeJs is easy to learn and code because it uses JavaScript. If you
are a front-end developer and have a good grasp of JavaScript you can easily learn and build
the application on NodeJS
5. Advantage of Caching: It provides the caching of a 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.
6. Data Streaming: In NodeJs 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.
7. Hosting: PaaS (Platform as a Service) and Heroku are the hosting platforms for NodeJS
application deployment which is easy to use without facing any issue.
8. Corporate Support: Most of the well-known companies like Walmart, Paypal, Microsoft,
Yahoo are using NodeJS for building the applications. NodeJS uses JavaScript, so most of
the companies are combining front-end and backend Teams together into a single unit.
Setting up Node.js and Other
Essentials: -
As with many technologies, it’s vital to have the proper foundation set up first, before moving on
to solving more
complex problems. In this chapter, we cover the following:
Node.js and (NPM) Node Package Manager installation•
Node.js script launches•
Node.js syntax and basics•
Node.js integrated development environments (IDEs) and code editors•
Awareness of file changes•
Node.js program debugging•
The installers come with NPM (Node Package Manager)— an important tool for managing
dependencies.
If there’s no installer for your OS (page http://nodejs.org/download/), you can get the
source code and
compile it yourself
Installing with HomeBrew or MacPorts-
If you already have HomeBrew (brew) installed, run the following in a straightforward manner:
$ brew install node
$ brew install npm
Similarly, for MacPorts, run
$ sudo port install nodejs
If your Mac OS X does not have HomeBrew, go to http://brew.sh/ or install it with the
following command:
$ ruby -e "$(curl -fsSL
https://raw.github.com/Homebrew/homebrew/go/install)"
Installing from a Tar File-
To install from a tar file (which is type of archive), set up a folder for the latest Node.js as follows:
$ echo 'export PATH=$HOME/local/bin:$PATH' >> ~/.bashrc
$ . ~/.bashrc
$ mkdir ~/local
$ mkdir ~/node-latest-install
$ cd ~/node-latest-install
Note:- if you find yourself getting errors when trying to install the module globally via npM
($ npm install -g <packagename>), reinstall node.js and npm with the “installing
Without sudo” solution below to eliminate the need to use sudo with the installation
command.
Installing Without sudo-
Sometimes, depending on your configuration, NPM asks users for sudo— root user permissions.
To avoid using sudo,
advanced developers can use the following::
$ sudo mkdir -p /usr/local/{share/man,bin,lib/node,include/node}
$ sudo chown -R $USER
/usr/local/{share/man,bin,lib/node,include/node}
Note:- please be sure you are comfortable with the functionality of the chown command
before you run it.
$ mkdir node-install
$ curl http://nodejs.org/dist/node-v0.4.3.tar.gz | tar -xzf - -C
node-install
$ cd node-install/*
$ ./configure
$ make install
$ curl https://npmjs.org/install.sh | sh
Installing from a Git Repo-
If you want to use the latest core Node.js code, and maybe even contribute to the Node.js and NPM
projects, it’s possible
to build the installation from the cloned Git repo. (This step requires Git. To install it, go to
http://git-scm.com/
and click Download.) For basic Git commands, refer to Chapter 11, where we explore deployment;
otherwise, do the
following:
1. Make the folders and add the path:
$ mkdir ~/local
$ echo 'export PATH=$HOME/local/bin:$PATH' >> ~/.bashrc
$ . ~/.bashrc
To clone the original Node.js repo from Joyent (alternatively, you can fork it and clone your own
repository),
do the following:
$ git clone git://github.com/joyent/node.git
$ cd node
$ ./configure --prefix=~/local
2. Make the build:
$ make install
$ cd ..
3. Repeat for NPM:
$ git clone git://github.com/isaacs/npm.git
$ cd npm
$ make install
For a more cutting-edge NPM version, use
$ make link
Multiversion Setup with Nave-
If you plan to run multiple versions of Node.js, use Nave
(https://github.com/isaacs/nave), which is a virtual
environment for Node.js. First, make a folder:
mkdir ~/.nave
cd ~/.nave
Then, download Nave and set the link to the PATH-ed folder:
$ wget http://github.com/isaacs/nave/raw/master/nave.sh
$ sudo ln -s $PWD/nave.sh /usr/local/bin/nave
An example of switching to Node.js version 0.4.8 with Nave in a virtual environment is as follows:
$ nave use 0.4.8
To use NPM in this particular virtual environment, use
$ curl https://npmjs.org/install.sh | sh
It is now possible to install something via NPM:
$ npm install express
Last, exit the virtual environment with
exit
More approaches to install Node.js and NPM are in gist
(https://gist.github.com/isaacs/579814)
Multiversion Setup with NVM-
Another option to Nave is NVM—Node Version Manager (GitHub,
https://github.com/creationix/nvm). Install
NVM as follows:
$ curl https://raw.github.com/creationix/nvm/master/install.sh |
sh
or
$ wget -qO-
https://raw.github.com/creationix/nvm/master/install.sh | sh
Then, harness NVM’s install:
$ nvm install 0.10
To switch to the 0.10 version, apply the use command. For example:
$ nvm use 0.10
You should see the latest versions of Node.js and NPM that you just downloaded and installed.
That’s it! You now have Node.js and NPM installed, and you should be ready to dig deeper into
using the platform.
The simplest way to run Node.js is through its virtual environment, which is often called read–
eval–print–loop, or REPL.
Node.js Console (REPL): -
Like most platforms/languages (e.g., Java, Python, Ruby, and PHP), Node.js comes with a virtual
environment: REPL.
Using this shell program, we can execute pretty much any Node.js/JavaScript code. It’s even
possible to include modules
and work with the file system! Other REPL use cases involve controlling nodecopters
(http://nodecopter.com/)
and debugging remote servers (more about this in Chapter 10). To start the console, run the
following command in
your terminal:
$ node
The prompt should change from $ to > (or something else, depending on your shell). From this
prompt, we can
run any JavaScript/Node.js (akin to the Chrome Developer Tools console) we want. For example:
> 1+1
> "Hello"+" "+"World"
> a=1;b=2;a+b
> 17+29/2*7
> f = function(x) {return x*2}
> f(b)
There are slight deviations in ECMAScript implementations in Node.js and browsers such as the
Chrome
Developer Tools console. For example, {}+{} is '[object Object][object Object]'
in Node.js REPL, whereas the
same code is NaN in the Chrome console because of the automatic semicolon insertion (ASI)
feature. However, for the
most part, Node.js REPL and the Chrome/Firefox consoles are similar
Launching Node.js Scripts: -
To start a Node.js script from a file, simply run $ node filename—for example, $ node
program.js. If all we need is
a quick set of statements, there’s a -e option that allows us to run inline JavaScript/Node.js—for
example, $ node -e
"console.log(new Date());"
If the Node.js program uses environmental variables, it’s possible to set them right before the
node command.
For example:
$ NODE_ENV=production API_KEY=442CC1FE-4333-46CE-80EE-6705A1896832
node server.
Loose typing
Buffer—Node.js super data type
Object literal notation
Functions
Arrays
Prototypal nature
Conventions
Node.js Core Modules: -
Unlike other programming technologies, Node.js doesn’t come with a heavy standard library. The
core modules of
node.js are a bare minimum, and the rest can be cherry-picked via the NPM registry. The main
core modules, classes,
methods, and events include the following:
• http (http://nodejs.org/api/http.html#http_http)
• util (http://nodejs.org/api/util.html)
• querystring (http://nodejs.org/api/querystring.html)
• url (http://nodejs.org/api/url.html)
• fs (http://nodejs.org/api/fs.html
http (http://nodejs.org/api/http.html)
http is the main module responsible for the Node.js HTTP server. The main methods are as
follows:
• http.createServer(): returns a new web server object
• http.listen(): begins accepting connections on the specified port and hostname
• http.createClient(): is a client and makes requests to other servers
• http.ServerRequest(): passes incoming requests to request handlers
• data: emitted when a part of the message body is received
• end: emitted exactly once for each request
• request.method(): the request method as a string
• request.url(): request URL string
• http.ServerResponse(): creates this object internally by an HTTP server — not by
the user— and is used as an output of request handlers
• response.writeHead(): sends a response header to the request
• response.write(): sends a response body
• response.end(): sends and ends a response body
util (http://nodejs.org/api/util.html)
The util module provides utilities for debugging. One method is as follows:
• util.inspect(): returns a string representation of an object, which is useful for debugging
querystring (http://nodejs.org/api/querystring.html)
The querystring module provides utilities for dealing with query strings. Some of the methods
include the following:
• querystring.stringify(): serializes an object to a query string
• querystring.parse(): deserializes a query string to an object
url (http://nodejs.org/api/url.html)
The url module has utilities for URL resolution and parsing. One method is as follows:
• parse(): takes a URL string and returns an object.
There is no need to install or download core modules. To include them in your application, all you
need is to use
the following syntax:
var http = require('http');
A list of noncore modules is found at the following locations:
npmjs.org• (https://npmjs.org): for the NPM registry
GitHub hosted list• (https://github.com/joyent/node/wiki/Modules): for
Node.js modules
maintained by Joyent
nodetoolbox.com• (http://nodetoolbox.com/): for a registry based on stats
Nipster• (http://eirikb.github.com/nipster/): for NPM search tools for Node.js
Node tracking (• http://nodejsmodules.org): for a registry based on GitHub stats
If you want to know how to code your own modules, take a look at the article “Your First Node.js
Module.”
Installing Node.js Modules with NPM: -
NPM comes with the Node.js platform and allows for seamless Node.js package management. The
way npm install
works is similar to Git in the way it traverses the working tree to find a current project
(https://npmjs.org/doc/
files/npm-folders.html). For starters, keep in mind that we need either the
package.json file or the node_modules
folder to install modules locally with $ npm install name. For example, $ npm install
superagent; in the program.
js write: var superagent = require('superagent');.
The best thing about NPM is that it keeps all the dependencies local, so if module A uses module B
v1.3, and
module C uses module B v2.0 (with breaking changes compared with v1.3), both A and C will
have their own localized
copies of different versions of B. This proves to be a more superior strategy than that of Ruby and
other platforms that
use global installations by default.
The best practice is not to include a node_modules folder in the Git repository when the
project is a module that
is supposed to be used in other applications. However, it’s recommended to include
node_modules for deployable
applications to prevent breakage caused by unfortunate dependency updates.
There’s nothing to be afraid of here as long as two-space indentation is used. ;-) However, callback
code can be
rewritten with the use of event emitters or promises, or by using the async library.
Hello World Server with HTTP Node.js Module-
Although, Node.js can be used for a wide variety of tasks, it’s used primarily for building web
applications. Node.js
thrives in the network as a result of its asynchronous nature and built-in modules such as net and
http.
Here’s a quintessential Hello World example in which we create a server object, define the request
handler
(function with req and res arguments), pass some data back to the recipient, and start up the
whole thing (hello.js):
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Let’s break it down a bit (if you know this already, skip to the next section). The following loads
the core http
module for the server (more on the modules later):
var http = require('http')
This snippet below creates a server with a callback function which contains the response handler
code:
var server = http.createServer(function (req, res) {
To set the right header and status code, use the following:
res.writeHead(200, {'Content-Type': 'text/plain'});
To output Hello World with the line end symbol, use
res.end('Hello World\n');
});
The req and res arguments have all the information about a given HTTP request and response
correspondingly.
In addition, req and res can be used as streams (see previous section).
To make the server accept requests, use the following:
... listen(1337, '127.0.0.1');
From the folder in which you have server.js, launch in your terminal the following command:
$ node server.js
Open localhost:1337 or 127.0.0.1:1337 or any other address you see in the terminal as a result of
the console.log()
function and you should see Hello World in a browser. To shut down the server, press Control + c
(on Mac OS X).
Here is what I have covered in this course: -
1. Foundations
2. Module System
3. Package Management
5. Web Servers
6. Express.js
Example app which blocks event loop + real life blocking functions
Node Cluster Module theory + in action
Clustering in the real world
Load balancing
PM2 theory + in action
Managing Live Clusters with PM2
Zero Downtime Restarts
Improving Performance of NASA Project
Stateless APIs
Node Worker Threads
9. Databases
11. Authentication
14. GraphQL
GraphQL vs REST
Building a GraphQL API
Sockets overview
Sockets vs polling
WebSockets (vs Socket io)
Socket io Client and Server APIs
Broadcasting Events
Build out Full Stack Multiplayer Pong with Sockets
Implementing Pong Game Logic
Using Socket io With Express.js
Namespaces and Rooms
Final Score: -
Assessment score-
Final Grade: -