CHAPTER:#5
Node js Modules
LECTTURER ENG: SAMATAR FIIDOW
Modules
• Consider modules to be the same as JavaScript
libraries.
• A set of functions you want to include in your
application
• Common js: every file is module(by default)
• Modules: Encapsulated code(only share minimum)
First Module
// names
const firtName = 'mohamed'
const lastName = 'Hassan'
// function
const sayHi = (name) => {
console.log(`Helo there ${name}`);
}
//invoking
sayHi(Mohamed')
sayHi(firtName)
sayHi(lastName)
Names separate file
// names
const firtName = 'mohamed'
const lastName = 'Hassan'
console.log(module);
module.exports= {firtName, lastName}
Utilities file
// function
const sayHi = (name) => {
console.log(`Helo there $
{name}`);
}
// export function
module.exports= sayHi
Access files
// access names
const names = require('./names')
// access function
const sayHi = require('./utilities')
sayHi('mohamed')
sayHi(names.firtName)
sayHi(names.lastName)
Built in modules
• Node.js has a set of built-in modules which you can use
without any further installation.
– OS: provides information operation system
– Path: to handle file paths
– FS: To handle file system
– HTTP: to make node.js act as an https server
– Net: to create servers and clients
Os module
const { log } = require('console')
const os = require('os')
// info about current user
const user = os.userInfo()
console.log(user);
// method return system uptime
console.log(`the system uptime is ${os.uptime}
seconds`);
Bunch info current system
const currentOs = {
name: os.type(),
release: os.release(),
totalMem: os.totalmem(),
freeMem: os.freemem(),
}
console.log(currentOs);
PATH - Module
• The path module in Node.js is a core module that
provides utilities for working with file and directory
paths. It helps normalize paths, join them, extract file
extensions, and more. You do not need to install it—
just require it
const path = require('path');
path.join([...paths])
• Joins multiple segments into one path (adds correct
slashes automatically).
const path = require('path');
const fullPath = path.join('folder',
'subfolder', 'file.txt');
console.log(fullPath); //
'folder/subfolder/file.txt'
path.resolve([...paths])
• Resolves a sequence of paths into an absolute path.
const path = require('path');
const absolutePath =
path.resolve('folder', 'file.txt');
console.log(absolutePath); // e.g.
'/Users/you/project/folder/file.txt
'
path.basename(p, [ext])
• Returns the filename part of a path, optionally
removing the extension.
const path = require('path');
console.log(path.basename('/folder/
file.txt')); // 'file.txt'
console.log(path.basename('/
folder/file.txt', '.txt'));//
'file'
path.dirname(p)
• Returns the directory portion of a path.
const path = require('path');
console.log(path.dirname('/folder/
subfolder/file.txt')); //
'/folder/subfolder'
path.parse(p)
• Returns an object with detailed parts of the path.
const path = require('path');
const parsed =
path.parse('/folder/file.txt');
console.log(parsed);
FS - Module (sync)
• The fs (File System) module in Node.js allows you to
interact with the file system. The sync (synchronous)
methods block the execution until the operation is
complete. They are simple and good for scripts or
when you don’t care about performance.
Read Fs-sync
const { readFileSync, writeFileSync} =
require('fs')
const first =
readFileSync('content/first.txt', 'utf-8')
const second =
readFileSync('content/second.txt', 'utf-
8')
console.log(first, second);
writeFileSync
writeFileSync('content/result.txt',
`here is the result :${first}, ${second}`,
{flag:'a'}
)
What is the HTTP Module
• The http module is a core (built-in) module in
Node.js that allows you to create HTTP servers
and handle HTTP requests and responses. It's the
foundation for building web applications and APIs
in Node.js without needing any third-party libraries.
Features of http Module
• Create a basic web server.
• Handle HTTP methods like GET, POST, PUT, DELETE.
• Read request data (URL, headers, body).
• Send responses (text, HTML, JSON, etc).
• Supports low-level HTTP functionality.
Http module(setup)
const http = require('http')
const server = http.createServer((req, res) => {
res.write('welcome to our first web server')
res.end()
})
server.listen(5000, () => {
console.log('the server is runing on localhost');
})
NPM
• NPM (Node Package Manager) is the default
package manager for Node.js, used to manage
JavaScript libraries and tools.
Key Concepts:
•Purpose: Automates the installation, versioning, and dependency
management of JavaScript packages.
•Registry: A public database (https://www.npmjs.com/) where developers
publish and share packages.
•CLI Tool: Comes bundled with Node.js.
•You use commands like
•npm install
•npm init, and npm run via the terminal.
How It Works:
•package.json: A file that stores metadata about your project and its
dependencies.
•node_modules/: A folder where installed packages are stored.
•npm install <package>: Installs a package and adds it to package.json.
package.json
• package.json is the metadata file at the root of a Node.js project that
defines the project and manages its dependencies.
Main Purposes:
•Describes your project (name, version, author, etc.)
•Lists dependencies (packages your project needs)
•Defines scripts to run tasks
•Sets configuration options
Example package.json
{
"name": "my-app",
"version": "1.0.0",
"description": "A sample Node.js app",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"No test yet\""
},
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"nodemon": "^2.0.22"
},
"author": "John Doe",
"license": "MIT"
}
What is Nodemon?
• Nodemon is a development tool for Node.js
that automatically restarts your application
whenever you make changes to the source
code.
Why Use Nodemon?
•No need to manually stop and restart your server after
every code change.
•It watches your files and reloads your app
instantlyGreat for Node.js development, especially
when working on backend servers
•npm install -g nodemon
Add to package.json Scripts
"scripts": {
"start": "node app.js",
"dev": "nodemon app.js"
}
Then run:
npm run dev
What is package-lock.json ?
• package-lock.json is an automatically
generated file in a Node.js project that locks
the exact versions of every installed package
and its dependencies.
Purpose
•Ensures consistent installs across different
environments.
•Tracks the exact version tree of all packages (even
nested ones).
•Improves performance and security scanning of
installs.
Key Differences from package.json
Feature package.json package-lock.json
Maintained by dev Manually edited or via npm Auto-generated by npm
Declares app metadata & Locks exact dependency
Purpose
deps tree
Exact resolved versions
Version format Ranges (e.g. ^1.2.3, ~4.0.0)
(e.g. 1.2.3)
Affects install order? No Yes
NodeJS Event Loop
The event loop in Node.js is a mechanism that allows asynchronous tasks to be handled
efficiently without blocking the execution of other operations. It:
– Executes JavaScript synchronously first and then processes asynchronous operations.
– Delegates heavy tasks like I/O operations, timers, and network requests to the libuv
library.
– Ensures smooth execution of multiple operations by queuing and scheduling callbacks
efficiently.
Why Event Loop is important?
• The Event Loop is essential in Node.js because it allows non-
blocking, asynchronous operations to be handled efficiently,
even though Node.js operates on a single thread.
– Enables non-blocking execution despite Node.js being single-
threaded.
– Helps handle I/O-bound tasks efficiently.
– Makes Node.js suitable for scalable applications like web servers.
Synchronous vs Asynchronous
Feature Synchronous Asynchronous
Blocking Yes No
Execution Order One task at a time Tasks can run concurrently
More efficient for I/O-
Performance Slower for I/O-heavy tasks
heavy tasks
More complex (needs
Complexity Simpler to understand
callbacks, promises, etc.)
How the Event Loop Works?
• When a Node.js application runs, the event loop starts,
processes the synchronous code first, and then moves to
handle asynchronous tasks. The execution follows these
steps:
1. Initialization
• When Node.js starts, it loads the script, executes
synchronous code, and registers any
asynchronous tasks (e.g., timers, I/O requests,
network operations).
2. Execution of Input Script
• The call stack executes synchronous code first.
• Any asynchronous operations (setTimeout,
fs.readFile, network requests) are delegated to
libuv.
3. Handling Asynchronous Operations with libuv
• Node.js uses a special C library called libuv to handle asynchronous operations. This
library manages a thread pool that offloads heavy tasks (like file I/O, database
operations, or network requests) that would otherwise block the event loop. The
thread pool contains several threads that perform tasks like:
– File system I/O (fs.readFile)
– Network requests (HTTP, TCP, DNS)
– Timers (setTimeout, setInterval)
– Compression and cryptographic tasks
the event loop in a Node.js server
Flow Overview:
•Requests Arrive ➝ go to the Event Queue
•Event Loop checks the queue:
•If it's a quick task → handled immediately
•If it's a slow/blocking task → sent to Thread Pool
•Thread Pool handles heavy tasks (e.g., file system, DB, network)
•When task is done, result goes back to Event Queue
•Event Loop picks it up again → sends response to the client
What are Streams?
• Streams are objects in Node.js that allow reading or
writing data piece by piece (chunks) instead of
loading the entire data into memory.
Why use Streams?
•Efficient memory usage.
•Better performance with large files or network
operations.
•Enables non-blocking I/O operations.
Types of Streams:
Type Description
Readable Can be read from (e.g., file read)
Writable Can be written to (e.g., file write)
Both readable and writable (e.g., TCP
Duplex
sockets)
Modifies data as it is read/written (e.g.,
Transform
compression)
Streams-Readfile
const fs = require('fs');
// Create a readable stream
const readStream = fs.createReadStream('example.txt', 'utf8');
// Listen for 'data' events to read chunks
readStream.on('data', (result) => {
console.log('Chunk received:', result);
});
// Listen for 'end' event to know when reading is complete
readStream.on('end', () => {
console.log('Finished reading the file.');
});
Streams-WriteFile
const fs = require('fs');
// Create a writable stream
const writeStream = fs.createWriteStream('output.txt');
// Write some text into the file
writeStream.write('Hello, this is the first line.\n');
writeStream.write('This is the second line.\n');
// End the stream (important to close it)
writeStream.end('Final line.');
// Handle finish event
writeStream.on('finish', () => {
console.log('Writing complete.');
});
Chalanage#1
Export and Import Multiple Values
– Create a names.js module that exports two
variables: firstName = "Amina" and lastName =
"Yusuf".
– Then, import and log them in another file.
Chalange#2
Use the os Built-in Module
• Write a program that uses the built-in os module to
display:
– The username
– System uptime (in seconds)
Chalange#3
• Use the built-in path module to:
– Join folder names: 'data', 'files', 'info.txt'
– Log the full joined path
Chalange#4
• Using the built-in http module, create a server that
listens on port
– 3000 and responds with:
– Welcome to my Node.js server!
Chalange#5
Write a script that creates a write stream to a file
note.txt and writes:
– This is a note written using stream.