0% found this document useful (0 votes)
13 views

NODEJS

Uploaded by

tashiki
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)
13 views

NODEJS

Uploaded by

tashiki
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/ 65

NODEJS

By Mr Smaranjit Ghose
What is NodeJS?
Node.js is an open-source and cross-platform JavaScript runtime environment.

Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the
browser. This allows Node.js to be very performant.

2
Key Features of NodeJS
● JavaScript Everywhere
Node.js lets you use JavaScript to write both the client-side and server-side of
your web applications. This means you can use the same programming language
for the entire web development process.

● Asynchronous and Non-blocking


Node.js can perform many operations at the same time without waiting for each
one to finish before starting the next. This makes it really efficient, especially for
tasks like accessing files or databases.

3
● Event Driven

In Node.js, your code reacts to different events. For example, it can run a function
as soon as it receives a request from a user. This event-driven nature helps in
handling multiple requests efficiently.

● Fast Performance

Node.js is built on the V8 JavaScript engine, which is the same engine that powers
Google Chrome. This makes Node.js very fast in executing JavaScript code

4
● NPM

Node.js comes with a huge collection of free, reusable code packages (libraries)
which can be managed easily called npm. This makes it easy to add new features
to your applications.

● Scalable

Node.js is great for building applications that need to handle lots of simultaneous
connections, like chat applications or real-time tracking systems. It can handle
many connections at once without using too much memory.

5
● Cross Platform

Node.js can run on various operating systems like Windows, MacOS, and Linux.
This makes it a versatile choice for different environments.

● Community Support

There's a large and active community of developers who use Node.js. This means
lots of support, tutorials, and third-party tools are available to help you.

6
Typical Use Cases of NodeJS
● Web Applications: Node.js is widely used to build fast and scalable web
applications. It's especially good for applications that require a persistent
connection from the browser to the server, like online games or chat
applications.

● API Development: Node.js, combined with frameworks like Express.js, is


great for creating RESTful APIs that can serve data to web apps, mobile apps,
or other internet-connected devices.

7
● Real-Time Applications: Its event-driven nature makes Node.js an excellent
choice for real-time applications such as instant messaging, video
conferencing apps, and online gaming. It can handle multiple client requests
efficiently, making it ideal for these scenarios

● Streaming Applications: Node.js can be used to build applications that


require streaming of data, such as live audio or video streaming platforms,
because of its ability to handle asynchronous data streams.

● Microservices Architecture: Node.js fits well in microservices architecture


due to its lightweight nature and the ability to handle diverse workloads,
which is essential in a microservices ecosystem.

8
● Single Page Applications (SPAs): Node.js can be used for server-side
rendering for SPAs, where the server returns an initial page and then new
pages are loaded dynamically as per user interaction, similar to desktop
applications

● Data-Intensive Real-time Applications (DIRT): Applications that require


real-time processing of a high volume of data, like online advertising
platforms or analytics dashboards, benefit from Node.js due to its
non-blocking I/O model.

● Command Line Tools: Apart from web applications, Node.js can also be used
to create command-line tools and scripts, enhancing productivity and
workflow automation

9
NODEJS SETUP
● Visit https://nodejs.org/en/download
● Select LTS
● Choose the appropriate installer as per your operating system

10
FIRST NODEJS PROGRAM
● Open the terminal
○ wt // For Windows users
● Make a new folder for your Node.js test project
○ mkdir nodedemo
● Navigate insider the new directory
○ cd nodedemo
● Create a new javascript file
○ touch app.js
● Open VS Code
○ code .
● Write the code `console.log(“This is my first NodeJS application`
● Back in the terminal, run the script with “node app.js”

11
Concepts to better understand
● HTML
● CSS
● JavaScript
● Basics of Computer Networking
● Client Server Model

12
NODEJS REPL
Node.js REPL (Read-Eval-Print Loop) is an interactive shell that allows you to run
JavaScript code in real-time. It's a powerful feature of Node.js, enabling quick
testing of JavaScript code snippets, debugging, and experimentation.

● Read: Reads user's input, parses the input into JavaScript data structure, and
stores it in memory.
● Eval: Takes and evaluates the data structure.
● Print: Prints the result.
● Loop: Loops back to the Read phase until the user presses Ctrl+C twice.

13
In the terminal, type node to start the shell

To exit the shell, type .exit in the terminal


14
REPL Features To Explore:

● Simple Javascript Expressions


● Use _ to get the last result
● Usage of Variables
● Multiline code/loops
● Using Editor Mode

15
Simple JavaScript Expressions

16
Using _ to get previous result

17
Using Variables

18
Multi-line Code

19
.editor Mode

20
NODEJS CORE MODULES
In Node.js, "core modules" refer to the set of modules that are part of the Node.js
runtime and are available by default without needing to install any additional
packages.

These core modules provide essential functionality for building a wide range of
applications in Node.js.

They are compiled into the binary distribution and load faster than external
modules because they are part of the Node.js runtime itself.

21
Brief Overview of Key Core Modules
fs (File System): Provides a way to interact with the file system, allowing you to
read from, write to, and manage files and directories.

http: Enables the ability to create HTTP servers and clients. It's fundamental for
building web applications in Node.js.

https: Similar to the http module but for creating HTTPS servers, which means it
handles communication over TLS/SSL

22
path: Provides utilities for working with file and directory paths. It's essential for
handling and transforming file paths in a consistent way across different
operating systems

os (Operating System): Offers basic operating-system related utility functions,


like getting the current user, system uptime, or memory usage.

util: Provides a collection of utility functions for debugging, inspecting objects,


and more.

events: Contains the EventEmitter class, which is key to working with


event-driven programming in Node.js. Many of the built-in modules use it.

23
stream: Provides an API for implementing data streaming functionality, such as
reading large files in chunks without reading them into memory.

buffer: Introduces the Buffer class, which provides a way to handle binary data.

querystring: Provides utilities for parsing and formatting URL query strings

url: Provides utilities for URL resolution and parsing, essential for web
applications and HTTP servers.

net: Offers an asynchronous network API for creating stream-based TCP or IPC
servers and clients.

24
To use a core module in Node.js, it can be invoked in the following way:

const <varirable_name> = require(`<module_name`)

25
fs Module
The fs module in Node.js is used for interacting with the file system. It provides a
wide array of functionalities to access and interact with the file system in a way
that is both synchronous (blocking) and asynchronous (non-blocking)

● Create a new directory

const fs = require(`fs`);
fs.mkdirSync(directoryName);
● Remove a pre-existing directory

const fs = require(`fs`);
fs.rmdirSync(directoryName);
26
● Writing data to a new file

const fs = require(`fs`);
fs.writeFileSync(filename, data);

27
● Writing data to a pre-existing file - overwrites the pre-existing
data

const fs = require(`fs`);
fs.writeFileSync(filename, data2);

28
● Appending data to a pre-existing file

const fs = require(`fs`);
fs.appendFileSync(filename, data);

29
● Renaming a pre-existing file

const fs = require(`fs`);
fs.renameSync(oldFileName, newFileName);

30
● Renaming a pre-existing file

const fs = require(`fs`);
fs.renameSync(oldFileName, newFileName);

31
● Reading a pre-existing file

const fs = require(`fs`);
fs.readFileSync(filename);

32
NOTE
● NodeJS uses a data type called Buffer while reading reading
from a file or receiving packets over the internet
● In order to retrieve the data, use the toString() method
● Alternatively, one can provide encoding “utf8” as an
argument to the readFileSync function

33
● Deleting a pre-existing file

const fs = require(`fs`);
fs.unlinkSync(fileName);

34
Asynchronous Operations

35
● Writing to a new file (Asynchronous)

36
Using a callback

37
NOTE

● A callback is a function passed as an argument to another function, which


can then be invoked inside the outer function to complete some kind of
routine or action. When dealing with asynchronous operations, callbacks are
essential for handling the results of those operations, such as reading from
or writing to a file, once they are completed.

38
● Appending to a pre-existing file (Asynchronous)

39
● Reading a pre-existing file (Asynchronous)

40
● Synchronous vs Asynchronous

41
os Module
The os module in Node.js is a built-in module used to provide operating
system-related utility methods and properties

● os.platform()

Returns a string identifying the operating system platform. For


example, it could return 'darwin', 'freebsd', 'linux', 'win32', etc.

const os = require(`os`);
console.log(os.platform());

42
● os.type()

Returns a string indicating the operating system name such as


“Darwin”, Windows_NT” or “Linux”. Similar to uname command in
CLI

const os = require(`os`);
console.log(os.type());
● os.version()

Returns a string that identifies the operating system version

const os = require(`os`);
console.log(os.version());

43
● os.arch()

Provides the operating system CPU architecture, for instance, 'x64',


'arm', etc

const os = require(`os`);
console.log(os.arch());

● os.hostname()

Returns the hostname of the operating system

const os = require(`os`);
console.log(os.hostname());

44
● os.freemem()

Shows the amount of free system memory in bytes as an integer.

const os = require(`os`);
let free_mem = os.freemem();
console.log(`Free Memory: ${free_mem/(1024*1024*1024)}`);

● os.totalmem()

Returns the total amount of system memory in bytes as an integer.

const os = require(`os`);
let total_mem = os.totalmem();
console.log(`Total Memory: ${total_mem/(1024*1024*1024)}`);
45
● os.homedir()

Provides the current user's home directory.

const os = require(`os`);
console.log(os.homedir());

● os.tmpdir()

Gives the default directory for temporary files.

const os = require(`os`);
console.log(os.tmpdir());

46
● os.uptime()

Provides the system uptime in seconds

const os = require(`os`);
console.log(`${os.uptime()/60}`);

● os.EOL

Provides the end-of-line marker for the current operating system.


For example, \n for POSIX and \r\n for Windows.

const os = require(`os`);
console.log(os.EOL());
47
● os.cpus()

Returns an array of objects containing information about each


logical CPU core.

const os = require(`os`);
console.log(os.cpus());

● os.networkInterfaces()

Lists network interfaces

const os = require(`os`);
console.log(networkInterfaces());

48
path Module
The path module in Node.js provides utilities for working with file and directory
paths. This is particularly useful since Windows and POSIX (Unix-like systems,
including Linux and macOS) have different path formats.

● path.dirname(path);

Returns the directories of a


path.

49
● path.basename(path);

Returns the last portion of a


path. Optionally, the file
extension can be removed.

● path.extname(path);

Returns the extension of the


path, from the last occurrence
of the . (period) character to end
of string in the last portion of
the path

50
● path.parse(path);

It is used to return an object


whose properties represent
the given path. This method
returns the following
properties:

● root (root name)


● dir (directory name)
● base (filename with
extension)
● ext (only extension)
● name (only filename)

51
● path.format(path);

It is used to compose a path string from an object. This object typically


contains certain properties that represent different segments of a path.

The method is essentially the opposite of path.parse(), which


decomposes a path string into its various components.

52
● path.normalize(path);

It normalizes a given path, resolving '..' and '.' segments and removing
redundant slashes. This method is useful for ensuring that a path is in a
consistent format. It doesn't necessarily return an absolute path, but it
cleans up the input path.

53
● path.isAbsolute(path);

Determines if the path is an


absolute path

54
Math module
In Node.js and JavaScript, there isn't a specific "math module" like in some other
programming languages. However, JavaScript has a built-in Math object that provides
many properties and methods for mathematical constants and functions. This Math
object is not a "module" because you don't need to import it using require or import -
it's available globally in any JavaScript environment.

NOTE: There is an external module Math.js that has extended capabilities such as
symbolic computations, chained operations and much larger set of functions and
constants

55
● Math.pow(x,y) - Returns x to the power of y
● Math.sqrt(x) - Returns the square root of x
● Math.cbrt(x) - Returns the cube root of x
● Math.exp(x) - Returns the exponential function of x (e^x)
● Math.log(x) - Returns the natural logarithm of x
● Math.log10(x) - Returns the logarithm of x with base 10
● Math.log2(x) - Returns the logarithm of x with base 2
● Math.round(x) - Returns x to the nearest integer
● Math.ceil(x) - Returns the smallest integer greater than x
● Math.floor(x) - Returns the largest integer less than x
● Math.abs(x) - Returns the absolute value of x
● Math.random(x) - Returns a pseudo-random number between 0 and 1

56
● Math.max(x,y..,z) - Returns the largest of the zero or more numbers given as
input parameters
● Math.min(x,y..,z) - Returns the smallest of the zero or more numbers given as
input parameters
TRIGONOMETRIC FUNCTIONS
● Math.sin(x)
● Math.cos(x)
● Math.tan(x)
● Math.asin(x)
● Math.acos(x)
● Math.atan(x)
CONSTANTS
● Math.PI - Returns the ratio of circumference of the circle to it’s diameter

57
Custom Module Creation
In Node.js, creating custom modules allows you to organize your code
into reusable and maintainable pieces.

Recap: A module is essentially a JavaScript file that encapsulates related


code into a single unit of functionality.

● Create a new JavaScript file, say arithmetic.js

touch arithmetic.js

58
● Now inside the arithmetic.js file create functions for addition,
subtraction, multiplication, division, modulo and power

59
● Use the module.exports to specify the functions that are enabled to
be exported to other files

60
● Now, inside a another javascript file, say index.js, use the require to
import the module.
● Ensure that the module is specified as a path like “./arithmetic”
instead of just the name “arithmetic”
● Extract all the functions under the same names as exported

61
● Once the functions are imported from the module, one can use
them seamlessly inside the index.js

62
Topics for upcoming lectures

● Creating your own module


● NPM
● Nodemon
● Module Wrapper
● HTTP Module
● NodeJS Routing
● JSON
● Simple
● Events Module
● Streams and Buffers
● Stream Pipes

63
T0 DO
● Practical 5 NODEJS CRUD OPERATIONS
● Practical 4 GitHub

64
65

You might also like