Node - Js Summary
Node - Js Summary
js
Node.js is able to perform a non-blocking I/O using only single thread by a mechanism
called “event loop”.
Async/await: a way to make the Asynchronous code to look as if it was synchronous.
Event Loop: a mechanism that allows Node.js to deal with heavy blocking tasks to external
threads which will make the Node.js program stay responsive.
How are asynchronous operations executed in Node?
Suppose the common task for a web server “open a file on the server and return the
content of it to the client”:
Node.js handles this file request is asynchronous manner:
1. Sends the task to the computer’s file system.
2. Ready to handle the next request.
3. When the file system has opened and read the file, the server returns the content to the
client.
This allows Node.js to handle all the requests using only a single thread.
Callback: Asynchronous equivalent for a function. It’s a technique in which a method calls
back the caller method.
Callback hell: a problem caused by callbacks, it made the code extremely unreadable and
missy.
Promises: introduced in EC6 (ECMAScript 6), helped solve the callback hell problem.
Promises are just objects that wrap any callback.
To use promises, we define new Object that takes a callback which receives 2 parameters:
resolve: called when the function succeeds (triggers.then)
reject: called when the function fails (triggers.catch)
Node Package Manager (NPM)
Where does the packages you install with NPM come from? www.npmjs.com
NPM subcommands: init, run.
npm init: initializes a Node.js project and create the “package.json” file.
npm install: installs all packages in “package.json” file.
npm install <package-name>: installs a package to node_modules and save it to
“package.json” under dependencies. (to make it dev-dependencies, use --save-dev)
npm run: sets the NODE environment variable to the node executable with which npm
is executed. It also lists the available scripts.
Adding scripts to be run by npm:
We can run scripts using npm by adding then to the “scripts” field in “package.json”
and run them with “npm run <script-name>”
Mention some popular npm packages and what they are used for briefly:
express: Fast, unopinionated, minimalist web framework for node. “express” provides
small, robust tooling for HTTP servers, making it a greate solution for single page
applications, websites, hybrid, or public HTTP APIs.
nodemon: is a tool that helps develop Node.js based applications by
automatically restarting the node application when file changes in the directory
are detected.
mongoose: is a MongoDB object modeling tool designed to work in an
asynchronous environment. Mongoose supports promises and callbacks.
joi: the most powerful schema description language and data validator for javascript.
REST
What is Rest?
REST is an acronym for REpresentational State Transfer and an architectural style for
distributed hypermedia systems. Roy Fielding first presented it in 2000 in his famous
dissertation.
Like other architectural styles, REST has its guiding principles and constraints.
These principles must be satisfied if a service interface needs to be referred to as
RESTful.
A Web API (or Web Service) conforming to the REST architectural style is a REST API.
Guiding Principles of REST:
Uniform Interface: By applying the principle of generality to the components interface,
we can simplify the overall system architecture and improve the visibility of interactions.
It has constraints to achieve REST interface:
Identification of resources
Manipulation of resources through representations
Hypermedia as the engine of application state
Client-server: The client-server design pattern enforces the separation of concerns,
which helps the client and the server components evolve independently. By separating
the user interface concerns (client) from the data storage concerns (server), we improve
the portability of the user interface across multiple platforms and improve scalability
by simplifying the server components.
Stateless: mandates that each request from the client to the server must contain all of
the information necessary to understand and complete the request. The server cannot
take advantage of any previously stored context information on the server.
Cacheable: The cacheable constraint requires that a response should implicitly or
explicitly label itself as cacheable or non-cacheable. If the response is cacheable, the
client application gets the right to reuse the response data later for equivalent requests
and a specified period.
Layered system: The layered system style allows an architecture to be composed
of hierarchical layers by constraining component behavior.
Code on demand (optional): REST also allows client functionality to extend
by downloading and executing code in the form of applets or scripts.
What is a Resource?
Any information that we can name can be a resource. For example, a REST resource can
be a document or image, a temporal service, a collection of other resources, or a non-
virtual object (e.g., a person). The state of the resource, at any particular time, is known
as the resource representation.
The resource representations consist of:
the data
the metadata describing the data
the hypermedia links that can help the clients in transition to the next desired
state. The data format of a representation is known as a media type like (JSON,
XML, HTML, plaintext)
self-descriptive: the client does not need to know if a resource is an employee or a
device. It should act based on the media type associated with the resource.
Resources Methods VS CRUD:
OPTIONS POST
GET PATCH
HEAD
PUT
DELETE
MongoDB Mongoose
Database management system Object document mapper
Stores large amount of data Manages relationship between data
Stores collections in database Define scheme for collections
SQL NoSQL
SQL databases are relational NoSQL databases are non-relational.
SQL databases use structured query NoSQL databases have dynamic schemas for
language and have a predefined schema unstructured data
SQL databases are table-based NoSQL databases are document, key-value, graph, or wide-
column stores
SQL databases are better for multi-row NoSQL is better for unstructured data like document of
transactions JSON
SQL databases are vertically scalable NoSQL databases are horizontally scalpel
These databases are not suited for These databases are best suited for hierarchical data storage.
hierarchical data storage.
These databases are best suited for These databases are not so good for complex queries
complex queries
Git & Github
Why use Git or version control in general (what problem does using Git solve):
With version control software such as “Git”, version control is much smoother and easier
to implement. Using an online platform like “Github” to store your files means that you
have an online backup of your work, which is beneficial for both you and your
collaborators.
Difference between git and github:
Git: is an open-source tool developers install locally to manage source code.
Github: is an online service to which developers who use “Git” can connect and upload
or download resources.
Git subcommands: Commit, branch, checkout, init.
git init: creates a new Git repository.
git commit: captures a snapshot of the project’s currently staged changes.
git branch: lets you create, list, rename, and delete branches.
git checkout: lets you navigate (switch) between the branches created by “git branch”.
Git best practice: never commit to main branch directly:
If a developer wants to commit changes to the source code, it’s better to make his/her
(new) own branch first, commits changes to it, and then issues a pull request to merge
this branch to the main branch. He/she should put some collaborator(s) as reviewer(s) to
check the merge request.
Conflicts, when the happen and how to fix them?
A conflict occurs when Git can’t figure out how to merge two branches automatically for
some reason, so it asks the developers to merge it manually by deciding which changes to
keep and which changes to drop.
OR: A conflict mainly occurr when two developers make change to same part of code
and Git can’t figure out which one should be kept. So, the developer who attempted to
merge later fails.
To resolve the conflict, the developer needs to pull the changes from the base branch
into his own, manually select the code blocks that he needs to keep, then create a commit
to save those changes, then retry merging with the base branch. This time Git can realize
that the coming changes are more recent than the changes it has, so it will accept the
coming updates.
Docker
Difference between docker image and container:
Docker Images: describe the applications and how they can be run.
Docker Containers: are the image instances, where multiple containers of the same
image can be run, each in a different state.
Docker subcommands: mainly run and build:
docker run: creates a container from a given image and starts the container using a
given command.
docker build: builds “Docker” images from a “Dockerfile” and a “context”. “context” of
a build is the set of files located in the specified PATH or URL.
Why use Docker: (what problem does using docker solve?):
Problems:
Compatibility of each service with the underlying OS.
Compatibility of each service with the libraries and dependencies of OS.
Every time version of any service updates, you need to recheck compatibilities
with underlying OS infrastructure.
“Matrix from Hell”.
For a new developer to setup the environment with right OS and Service versions.
Docker Solution:
Each service has and can manage its required OS dependencies for itself, bundled
and isolated in its own container.
Change the components without affecting the other services.
Change underlying OS without affecting any of the services.
As a result, docker should avoid the typical “works on my machine” cases. In
development process, developers and testers will have the identical environments where
the applications runs, since this environment is packaged in docker containers, which
just like a file, can be transferred around as an artifact.
Docker features:
Modularity.
Layers and image version control.
Rollback to previous versions.
Rapid deployment.