KEMBAR78
2 Introduction To Node | PDF | Java Script | Computer Programming
0% found this document useful (0 votes)
17 views9 pages

2 Introduction To Node

Uploaded by

Tomo Hoshii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views9 pages

2 Introduction To Node

Uploaded by

Tomo Hoshii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Introduction to Node.

js

Imagine a world where the same language you use to build interactive web pages in the
browser could also power the servers that deliver those pages. This is the promise of Node.js.
It's not just another programming language; it's a runtime environment that allows you to
execute JavaScript on the server-side, opening up a universe of possibilities for web
development. Node.js has revolutionized the way we build web applications, enabling
developers to write fast, scalable, and efficient server-side code using the familiar syntax of
JavaScript. Node.js was initially created by Ryan Dahl in 2009. He envisioned a runtime that
could handle numerous concurrent connections efficiently, addressing the limitations of
traditional server-side technologies. Today, Node.js is maintained and developed by the
OpenJS Foundation, a collaborative community of companies and individuals dedicated to
supporting the growth and sustainability of the Node.js ecosystem. This open governance
ensures that Node.js remains a robust and evolving platform, benefiting from the collective
expertise of its contributors. This lecture will guide you through the fundamental concepts
of Node.js, explore its unique architecture, and demonstrate how to create a basic web server.
We'll delve into the power of npm, the Node Package Manager, and understand why Node.js
is a game-changer in modern web development.

What is Node.js?
Node.js is a runtime environment that enables you to execute JavaScript code outside of a
web browser. Traditionally, JavaScript was confined to the client-side, running within the
browser to enhance user interfaces. Node.js, built on Chrome's V8 JavaScript engine, breaks
those boundaries. It allows you to use JavaScript for server-side scripting, creating web
servers, handling file system operations, and building network applications.

• Defining Node.js:

o Node.js is a runtime environment, meaning it provides the necessary tools and


libraries to execute JavaScript code. Think of it as a platform that allows
JavaScript to run on your computer's operating system, not just within a
browser.

o It's built on Chrome's V8 JavaScript engine. The V8 engine is the same engine
that powers Google Chrome. It's known for its high performance, as it compiles
JavaScript code into native machine code, making it very fast.
o Node.js is open-source and cross-platform. This means it's freely available and
can run on various operating systems like Windows, macOS, and Linux.

• Key Characteristics:

o Asynchronous, Event-Driven, Non-Blocking I/O:

▪ This is the core of Node.js's efficiency. In traditional synchronous I/O, if


a program needs to wait for an operation (like reading a file), it blocks
and waits. In Node.js, operations are asynchronous. When a task
requires waiting, Node.js continues executing other tasks, and when the
waiting is over, it uses events to trigger a callback function to handle the
result. This non-blocking behavior is crucial for handling multiple
concurrent requests without slowing down.

o Single-Threaded:

▪ Node.js runs on a single thread. This might seem like a limitation, but
because of its non-blocking I/O model, it can handle a large number of
concurrent connections efficiently. The event loop manages the
execution of asynchronous operations, ensuring that the single thread
is never blocked.

o JavaScript Everywhere:

▪ Node.js allows you to use JavaScript for both the front-end (client-side)
and back-end (server-side) of your web applications. This enables full-
stack JavaScript development, simplifying the development process
and promoting code reuse.

• Why Node.js?

o Performance:

▪ Node.js's non-blocking I/O model makes it highly efficient for handling


I/O-bound operations, such as network requests and file system
operations.

o Scalability:

▪ Its ability to handle a large number of concurrent connections makes it


ideal for building scalable applications.
o Unified Development:

▪ Using JavaScript for both front-end and back-end simplifies


development and reduces the need for context switching between
different languages.

o Large Ecosystem:

▪ npm (Node Package Manager) provides access to a vast library of


modules, making it easy to add functionality to your Node.js
applications.

Node.js Architecture and Concepts


• V8 Engine:

o The V8 engine, developed by Google, is the heart of Node.js. It's a high-


performance JavaScript engine that compiles JavaScript code into native
machine code. This compilation happens just-in-time (JIT), meaning the code
is compiled as it's being executed. This results in faster execution speeds
compared to interpreted languages.

• Event Loop:

o The event loop is the mechanism that allows Node.js to perform non-blocking
I/O operations. It continuously monitors the call stack and the callback queue.
When an asynchronous operation completes, its callback function is moved
from the callback queue to the call stack, and the event loop executes it.

o Example:

console.log('Start');

setTimeout(() => {

console.log('Timeout callback');

}, 0);

console.log('End');
▪ In this example, "Start" and "End" are printed immediately. The
setTimeout function schedules the callback to be executed after 0
milliseconds. However, the callback is not executed immediately.
Instead, it's placed in the callback queue. The event loop then moves the
callback to the call stack after the "End" statement has been executed.
So, the output is "Start," "End," and then "Timeout callback."

• Non-Blocking I/O:

o Blocking I/O means that a program waits for an operation to complete before
continuing. Non-blocking I/O means that the program can continue executing
other tasks while waiting for an operation to complete.

o Example:

const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {

if (err) {

console.error(err);

return;

console.log(data);

});

console.log('Reading file asynchronously...');

▪ In this example, the fs.readFile function reads a file asynchronously. The


program doesn't wait for the file to be read. Instead, it immediately
prints "Reading file asynchronously..." The callback function is executed
when the file reading is complete, and the file's contents are printed.
Node.js Runtime and npm
• Node.js Installation:

o Node.js can be downloaded and installed from the official Node.js website
(nodejs.org). After installation, you can verify the installation by running node
-v and npm -v in your terminal.

• Node.js REPL (Read-Eval-Print Loop):

o The REPL is an interactive shell that allows you to execute JavaScript code line
by line. It's useful for testing code snippets and experimenting with Node.js.

• npm (Node Package Manager):

o npm is the default package manager for Node.js. It allows you to install, update,
and uninstall Node.js packages.

o Example:

Bash

npm install express

npm install lodash

▪ The npm install command downloads and installs the specified


packages and their dependencies. The packages are stored in the
node_modules folder.

• package.json:

o The package.json file is a JSON file that contains metadata about your Node.js
project. It lists the project's dependencies, scripts, and other information.

o You can create a package.json file by running npm init -y.

o The dependencies field lists the packages that your project depends on. The
devDependencies field lists the packages that are used for development
purposes.

o The scripts field allows you to define custom scripts that can be executed using
npm run <script-name>.
Creating a Simple Node.js Server
• Setting Up a Project:

o Create a new project directory and initialize a package.json file using npm init
-y.

o Install the http module, which is a core Node.js module for creating HTTP
servers.

• Building a Basic HTTP Server:

o Example:

const http = require('http');

const server = http.createServer((req, res) => {

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

res.end('Hello, Node.js!\n');

});

const port = 3000;

server.listen(port, () => {

console.log(`Server running at http://localhost:${port}/`);

});

▪ The http.createServer() method creates an HTTP server. The callback


function is executed for each incoming request.

▪ The res.writeHead() method sets the HTTP status code and headers.

▪ The res.end() method sends the response body.

▪ The server.listen() method starts the server and listens for incoming
connections on the specified port.

• Handling Different Routes:

o Example:

const http = require('http');


const server = http.createServer((req, res) => {

if (req.url === '/') {

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

res.end('Welcome to the home page!\n');

} else if (req.url === '/about') {

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

res.end('About Node.js\n');

} else {

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

res.end('404 Not Found\n');

});

const port = 3000;

server.listen(port, () => {

console.log(`Server running at http://localhost:${port}/`);

});

▪ This example shows how to handle different URL paths using req.url.

• Serving HTML Files:

o Example:

const http = require('http');

const fs = require('fs');

const server = http.createServer((req, res) => {

fs.readFile('index.html', 'utf-8', (err, data) => {


if(err){

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

res.end('404 Not Found');

} else {

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

res.end(data);

});

});

const port = 3000;

server.listen(port, () => {

console.log(`Server running at http://localhost:${port}/`);

});

▪ This example shows how to serve HTML files using the fs module.

The Significance of Node.js

• Real-Time Applications:
o Node.js's event-driven architecture makes it ideal for real-time applications,
such as:
▪ Chat applications: Think of applications like Slack or Discord, where
messages need to be delivered instantly to multiple users. Node.js
excels at handling the constant flow of data.
▪ Online games: Multiplayer games requiring real-time updates, like
online chess or collaborative gaming platforms, benefit from Node.js's
low latency.
▪ Live dashboards: Financial dashboards, monitoring systems, and live
sports updates that need to display data as it changes, can be
efficiently built using Node.js.
▪ Streaming applications: Applications like those used to stream
video, or audio data, or live data from IOT devices.
• Microservices Architecture:
o Node.js is well-suited for building microservices, which are small,
independent services that work together to form a larger application.
▪ E-commerce platforms: An e-commerce site might use microservices
for user authentication, product catalog management, and payment
processing, each handled by separate Node.js services.
▪ Content delivery networks (CDNs): CDNs can use Node.js
microservices to manage content caching and delivery across
different servers.
▪ API Gateways: Node.js can be used to create API gateways that route
requests to different microservices.
• Full-Stack Development:
o Using JavaScript for both front-end and back-end simplifies development and
promotes code reuse.
▪ MEAN/MERN stack applications: These stacks leverage MongoDB,
Express.js, Angular/React, and Node.js, enabling developers to build
complete web applications using only JavaScript.
▪ Single-page applications (SPAs): SPAs, which rely heavily on
JavaScript for dynamic content, can be seamlessly integrated with
Node.js back-ends.
• Popular Frameworks:
o Frameworks like Express.js, Nest.js, and Koa.js provide additional tools and
abstractions for building Node.js applications.
▪ Express.js: Used for building robust web APIs and server-side
applications.
▪ Nest.js: A framework for building scalable and maintainable server-
side applications using TypeScript.
▪ Koa.js: A lightweight framework that provides a more expressive and
enjoyable way to build web applications and APIs.

You might also like