[go: up one dir, main page]

0% found this document useful (0 votes)
42 views10 pages

Node - Js and Express - Js - Comprehensive Guide

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)
42 views10 pages

Node - Js and Express - Js - Comprehensive Guide

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/ 10

Node.js and Express.

js – Comprehensive Guide
Node.js Overview
Node.js is an open-source, cross-platform JavaScript runtime built on Chrome’s V8 engine 1 . Unlike
browser JS, Node runs on the server, using an event-driven, non-blocking I/O model. In practice, a Node.js
application runs as a single process (single thread) that handles many concurrent connections by offloading
I/O to the operating system. This design allows a Node.js server to efficiently manage thousands of clients
simultaneously 2 3 . For example, the simplest HTTP server in Node uses the built-in http module:

const { createServer } = require('node:http');


const server = createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(3000, () => { console.log('Server running'); });

This code creates a server that listens on port 3000 and responds “Hello World” to any request 4 5 .
Notice how we import modules (here node:http ) with require() and use res.end() to send a
response.

Node.js Basics and Setup


To get started, install Node.js (which includes npm, the Node package manager) from the official site or via
your OS package manager. Once Node is installed, you can verify it with node --version and npm --
version . MDN notes that Node and npm are bundled together and can be installed from binaries or
source 6 . It is generally recommended to use an LTS (Long-Term Support) release of Node for production
stability 7 . On Windows, you can use the MSI installer; on macOS/Linux, installers or package managers
like Homebrew/Apt can be used.

After installation, you typically initialize a project with npm init to create a package.json . The npm
install <package> command installs libraries and their dependencies into your project 8 . For
example, npm install express --save adds Express to your project. You can install global tools (like
npx or nodemon ) with npm install -g <tool> . The npx command (included with npm) lets you run
CLI tools without installing them globally. For instance, npx express-generator runs the Express
project generator tool without separate install 9 .

1
Node.js Console & REPL
Node.js provides a built-in interactive shell called the REPL (Read-Eval-Print Loop) 10 . Start it by simply
running node in a terminal 11 . The REPL prompt > lets you type JavaScript expressions on the fly. For
example:

> 2 + 3
5
> console.log("Hello");
Hello
undefined

This makes it easy to test code quickly 12 . In your Node scripts and the REPL, use the global console
object for debugging output. The Node console module provides familiar methods like
console.log() , console.error() , and console.warn() 13 . For instance,
console.log('hello world') prints to standard output 14 . Unlike browsers, Node’s global console
writes to process.stdout and process.stderr , and console.log does not return a value (it prints
and returns undefined ) 13 14 .

Node.js Command-Line Utilities


Node comes with useful CLI tools. The most basic is running your script: if you save code in server.js ,
run it via node server.js 15 . Npm (Node Package Manager) provides commands to manage packages.
Key commands include:

• npm init – create a new package.json (project manifest). It interactively asks questions and
generates the file.
• npm install <pkg> – install a package (and its dependencies) to node_modules 8 . E.g.
npm install express .
• npm install -g <tool> – install a tool globally so it’s on your PATH (e.g. npm install -g
nodemon ).
• npm list – list installed packages.
• npx <command> – run an executable package. For example, the Express app generator: npx
express-generator 9 .

These utilities let you scaffold and manage projects efficiently. For example, the Express generator (covered
below) is often run via npx .

Node.js Modules
Modules in Node.js are self-contained files of code that can be loaded and reused 16 . Node has many built-
in modules (like http , fs , path , etc.) you load with require() . For example:

2
const fs = require('fs');
fs.readdir('.', (err, files) => {
console.log(files);
});

This uses the built-in fs module to read directory contents 17 .

You can also write custom modules. Any .js file becomes a module. You export values by attaching them
to module.exports or exports . For example, in user.js:

exports.getName = () => 'Alice';

and in app.js:

const user = require('./user');


console.log(`Name: ${user.getName()}`);

This shows defining a function in one file and importing it in another 18 . In modern Node, you can also use
ES modules ( import / export ) by using the .mjs extension or setting "type": "module" in
package.json . Modules help you organize code and share functionality.

Node.js Core Concepts (Event Loop & Asynchrony)


A key concept in Node is its single-threaded event loop. As Node’s documentation explains, the event loop
“allows Node.js to perform non-blocking I/O operations — despite the fact that a single JavaScript thread is
used by default” 3 . In practice, this means: when you perform an I/O operation (disk access, network
request, etc.), Node does not block the main thread. Instead, it delegates the task to the operating system
(which can handle many tasks in parallel). When the I/O finishes, a callback is queued and eventually
executed by the event loop 2 3 .

The typical architecture is illustrated below:

Figure: Node.js server architecture – incoming requests enter an event queue, then are handled one by one
by the event loop. Non-blocking requests are processed immediately, while blocking tasks are offloaded to a
thread pool or external resources 19 .

In this design, Node’s Event Queue holds pending requests, and the Event Loop continuously takes the
next request and processes it 19 . Simple (non-blocking) requests are handled in the main thread. If a
request involves blocking work (e.g. file I/O), Node assigns a thread from a pool to perform that work. When
the thread completes, the event loop receives the result and continues processing. This means a single
Node process can handle many clients with fewer system resources 19 2 .

3
Another consequence is that Node code should avoid blocking operations on the main thread. Long loops
or heavy computations will freeze the event loop. Instead, most APIs are asynchronous (taking callbacks,
Promises, or using async/await ). This asynchrony lets Node maximize throughput.

Node.js Events
Node.js provides an EventEmitter class for handling custom events. Many built-in objects (like streams) use
this. You can create your own event emitter:

const EventEmitter = require('events');


const emitter = new EventEmitter();
emitter.on('greet', (name) => {
console.log(`Hello, ${name}!`);
});
emitter.emit('greet', 'Bob'); // outputs: Hello, Bob!

Here, on('greet',…) listens for the 'greet' event, and emit('greet', data) triggers it. As
Node’s docs show, use on() to register a callback and emit() to fire an event 20 . This pattern is
fundamental in many Node APIs.

Node.js Database Access


Node.js can connect to databases using various drivers. You install a driver via npm and then require()
it. For example:

• MySQL: After installing the mysql package ( npm install mysql ), use it as follows 21 :

const mysql = require('mysql');


const con = mysql.createConnection({host:"localhost", user:"root",
password:"pass"});
con.connect(err => {
if (err) throw err;
console.log("Connected to MySQL!");
});

This uses the popular mysql NPM module to connect to a MySQL database 21 .

• MongoDB: The official MongoDB driver ( mongodb package) is installed via npm install
mongodb 22 . You then use MongoClient to connect:

const { MongoClient } = require('mongodb');


const uri = 'mongodb://localhost:27017/mydb';

4
const client = new MongoClient(uri);
await client.connect();

As MongoDB docs explain, MongoClient is used to connect and perform operations 23 .

Similarly, drivers exist for PostgreSQL ( pg package), SQLite ( sqlite3 ), Redis, and others. Once
connected, you execute queries or commands and handle results via callbacks or Promises. Express (below)
is often used on top of Node to build APIs that interface with databases in this way.

Node.js with Express.js


Express.js is a widely-used, unopinionated web framework built on Node.js. It “sits on top of Node.js’s web
server functionality” to simplify routing and middleware 24 . In Express, you create an app and define
routes for different HTTP methods. For instance, the classic Express “Hello World” looks like this 25 :

const express = require('express');


const app = express();
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(3000, () => {
console.log("Server listening on port 3000");
});

Here, app.get("/", ...) defines a handler for GET requests to the root path. The handler receives a
request ( req ) and a response ( res ) object, and sends “Hello World” back to the client 25 26 .

Express.js Request Object

In any route, Express provides a req (request) object representing the incoming HTTP request. It contains
details such as route parameters, query string, headers, and body. For example, req.params holds URL
parameters, req.query holds URL query parameters, and req.body (after using body-parsing
middleware) holds form or JSON data. DigitalOcean notes that Express receives client data through
req.params , req.query , and req.body 27 . For example, in
app.get('/user/:id', (req, res) => { ... }) , req.params.id contains the value from the
URL.

Express.js Response Object

The res (response) object is used to send a response back to the client. It has methods like
res.send() , res.json() , res.redirect() , and res.status() . In the example above, calling
res.send("Hello World!") sends that string to the browser 26 . Other common patterns include:
- res.json(obj) – send a JSON response (sets Content-Type: application/json ).
- res.status(code).send(message) – set the HTTP status code and send a message.
- res.redirect(url) – redirect the client to another URL.

5
For instance, res.status(200).json({ success: true }) would send a JSON body with status 200.
These methods make it easy to control HTTP responses in Express.

Express.js GET and POST

Express routes are defined by HTTP method. For GET requests, use app.get(path, handler) . For
POST, use app.post(path, handler) . In the earlier example, app.get('/', (req, res) =>
{ res.send('Hello World!'); }) sets up a GET handler 25 . Similarly, an example POST route could
be:

app.post('/submit', (req, res) => {


res.send('POST request to /submit');
});

For example, Express’s API docs show:

app.post('/', (req, res) => {


res.send('POST request to homepage');
});

This handles POST requests to / and sends a response 28 . In practice, req.body (with middleware)
would carry form or JSON data from the client.

Express.js Routing

Routing in Express maps URL patterns and methods to handlers. You define routes like app.get('/
users/:id', handler) , where :id is a parameter. Express also supports the Router() class to
create modular route handlers. For example:

const router = express.Router();


router.get('/items', (req, res) => { /* ... */ });
app.use('/api', router);

This mounts the router so that /api/items is handled by the defined function. Order matters: routes and
middleware are processed in the order they are added. Express’s flexible routing allows middleware and
handlers to be applied at both application and router levels 29 .

Express.js Cookies

To handle cookies, Express uses middleware such as cookie-parser . This middleware parses the
Cookie HTTP header and populates req.cookies (and req.signedCookies for signed cookies) 30 .
For example:

6
const cookieParser = require('cookie-parser');
app.use(cookieParser()); // must do before reading cookies
// Later in a handler:
console.log(req.cookies); // an object of cookie name/value pairs

You can set cookies in responses using res.cookie(name, value, options) . For example,
res.cookie('token', 'abc123', { httpOnly: true }) sets a cookie. In summary, cookie-
parser makes incoming cookies accessible via req.cookies 30 .

Express.js File Upload

For handling file uploads (multipart form data), Express commonly uses the multer middleware. Multer
processes multipart/form-data and makes uploaded files available in the req object. According to
the official docs: Multer adds a body object (for text fields) and a file or files object to the req
31 . For example, to upload a single file named “avatar”:

const multer = require('multer');


const upload = multer({ dest: 'uploads/' });
app.post('/profile', upload.single('avatar'), (req, res) => {
// req.file is the uploaded file
// req.body contains other form fields
});

Here, upload.single('avatar') parses the incoming form, saving the file to uploads/ and placing
info in req.file . Multer also supports upload.array() for multiple files, and upload.fields() for
mixed fields 31 .

Express.js Middleware

Middleware functions in Express are functions that have access to the request and response objects, and
can modify them or terminate the request. They have the signature (req, res, next) . Middleware can
perform tasks like logging, authentication, parsing JSON, etc. After doing its work, it must call next() to
pass control to the next middleware or route handler 32 . The order of middleware is determined by the
order of app.use() or route definitions; the first matching middleware runs first 29 . For example:

// Example middleware:
function myLogger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next(); // continue processing
}
app.use(myLogger); // applies to all routes

7
Built-in middleware (like express.json() to parse JSON bodies) and third-party middleware (like cors ,
morgan , etc.) are commonly added via app.use() . You can also attach middleware to specific routes
(e.g., app.get('/', authMiddleware, handler) ). The key point is that middleware functions
augment request processing, and they always call next() unless they end the response 32 29 .

Express.js Scaffolding

Express provides a project generator tool called express-generator to scaffold a new application. This
creates a directory structure with boilerplate code. For example, with Node 8.2.0+, you can run:

npx express-generator --view=pug myapp

This creates a new folder myapp set up with the Pug template engine (shown in the docs) 33 . If using
older Node versions, you’d first install it globally: npm install -g express-generator and then run
express myapp 34 . The generator outputs files like app.js , routes/ , views/ , and so on, giving
you a ready-to-run app. After creation, you cd myapp && npm install to install dependencies, then
npm start to run. Scaffolding is optional but speeds up setup 33 .

Express.js Template Engines

Express can render HTML views using templating engines. A template engine lets you write HTML pages
with placeholders for data. Express does not include an engine by default, but supports many (e.g., Pug,
EJS, Handlebars). First, install the engine via npm (e.g. npm install pug ). Then configure Express:

app.set('views', './views'); // directory for template files


app.set('view engine', 'pug'); // use Pug as the view engine

(If using Express Generator, it sets defaults for you.) You do not need to require('pug') manually after
this – Express loads it automatically 35 .

Once set up, you can render a template with:

res.render('index', { title: 'Home', message: 'Welcome!' });

This looks for views/index.pug (or .ejs , etc.) and injects the provided variables. For example, if
views/index.pug contains:

html
head
title= title
body
h1= message

8
then res.render('index', {title: 'Hey', message: 'Hello there!'}) will generate an HTML
page with <title>Hey</title> and <h1>Hello there!</h1> 35 36 . The final HTML is sent back to
the client. Express also caches templates and only re-renders them per request (not per template load).

Sources: Authoritative Node.js and Express.js documentation and tutorials have been used throughout. All
quoted material and code examples above are cited accordingly 1 16 20 8 13 37 30 31 32 9 35
3 19 27 28 .

9
1 2 4 5 15 Node.js — Introduction to Node.js
https://nodejs.org/en/learn/getting-started/introduction-to-nodejs

3 Node.js — The Node.js Event Loop


https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick

6 7 Setting up a Node development environment - Learn web development | MDN


https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/
development_environment

8 npm-install | npm Docs


https://docs.npmjs.com/cli/v9/commands/npm-install/

9 33 34 Express application generator


https://expressjs.com/en/starter/generator.html

10 11 12 Node.js REPL Terminal Overview


https://www.tutorialspoint.com/nodejs/nodejs_repl_terminal.htm

13 14 Console | Node.js v24.2.0 Documentation


https://nodejs.org/api/console.html

16 17 18 Understanding module.exports and exports in Node.js — SitePoint


https://www.sitepoint.com/understanding-module-exports-exports-node-js/

19 Node.js Web Application Architecture - GeeksforGeeks


https://www.geeksforgeeks.org/node-js/node-js-web-application-architecture/

20 Node.js — The Node.js Event emitter


https://nodejs.org/en/learn/asynchronous-work/the-nodejs-event-emitter

21 Node.js MySQL
https://www.w3schools.com/nodejs/nodejs_mysql.asp

22 23 Connect to a MongoDB Database Using Node.js | MongoDB Blog


https://www.mongodb.com/blog/post/quick-start-nodejs-mongodb-how-to-get-connected-to-your-database

24 Explain the use of req and res objects in Express JS - GeeksforGeeks


https://www.geeksforgeeks.org/node-js/explain-the-use-of-req-and-res-objects-in-express-js/

25 26 29 32 37 Express/Node introduction - Learn web development | MDN


https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Introduction

27 How To Use the req Object in Express | DigitalOcean


https://www.digitalocean.com/community/tutorials/nodejs-req-object-in-expressjs

28 Express 5.x - API Reference


https://expressjs.com/en/api.html

30 Express cookie-parser middleware


https://expressjs.com/en/resources/middleware/cookie-parser.html

31 Express multer middleware


https://expressjs.com/en/resources/middleware/multer.html

35 36 Using template engines with Express


https://expressjs.com/en/guide/using-template-engines.html

10

You might also like