NODEJS
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.
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.
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
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
● 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
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
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:
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)
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
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()
const os = require(`os`);
console.log(os.platform());
42
● os.type()
const os = require(`os`);
console.log(os.type());
● os.version()
const os = require(`os`);
console.log(os.version());
43
● os.arch()
const os = require(`os`);
console.log(os.arch());
● os.hostname()
const os = require(`os`);
console.log(os.hostname());
44
● os.freemem()
const os = require(`os`);
let free_mem = os.freemem();
console.log(`Free Memory: ${free_mem/(1024*1024*1024)}`);
● os.totalmem()
const os = require(`os`);
let total_mem = os.totalmem();
console.log(`Total Memory: ${total_mem/(1024*1024*1024)}`);
45
● os.homedir()
const os = require(`os`);
console.log(os.homedir());
● os.tmpdir()
const os = require(`os`);
console.log(os.tmpdir());
46
● os.uptime()
const os = require(`os`);
console.log(`${os.uptime()/60}`);
● os.EOL
const os = require(`os`);
console.log(os.EOL());
47
● os.cpus()
const os = require(`os`);
console.log(os.cpus());
● os.networkInterfaces()
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);
49
● path.basename(path);
● path.extname(path);
50
● path.parse(path);
51
● path.format(path);
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);
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.
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
63
T0 DO
● Practical 5 NODEJS CRUD OPERATIONS
● Practical 4 GitHub
64
65