NODE JS NOTES
NodeJS
1. Introduction to NodeJS
Overview: NodeJS is a JavaScript runtime built on Chrome's V8 JavaScript engine,
allowing developers to run JavaScript on the server side.
Key Features:
1. Event-driven architecture
2. Non-blocking I/O operations
3. Single-threaded but highly scalable due to the event loop
Example: Basic server setup
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
2. Setting Up a NodeJS Project.
Project Initialization: Use npm init to create package.json.
npm init -y
npm install express --save
3. Understanding Modules and npm
Modules: Encapsulated code that can be reused across different parts of an application
or by other applications.
npm: Package manager for JavaScript.
// Importing a module
const fs = require('fs');
// Using a module
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
4. Building a Web Server with NodeJS
HTTP Module: Fundamental for creating HTTP servers.
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello World</h1>');
}).listen(3000, () => {
console.log('Server running on port 3000');
});
5. Serving Static Files
File Serving: Using fs module to read and serve files.
const http = require('http');
const fs = require('fs');
const path = require('path');
http.createServer((req, res) => {
let filePath = '.' + req.url;
if (filePath == './') filePath = './index.html';
const extname = path.extname(filePath);
let contentType = 'text/html';
switch (extname) {
case '.js': contentType = 'text/javascript'; break;
case '.css': contentType = 'text/css'; break;
// Add more types as needed
}
fs.readFile(filePath, (err, content) => {
if (err) {
if(err.code == 'ENOENT') {
fs.readFile('./404.html', (err, content) => {
res.writeHead(404, { 'Content-Type': contentType });
res.end(content, 'utf-8');
});
} else {
res.writeHead(500);
res.end('Sorry, check with the site admin for error: '+err.code+' ..\n');
res.end();
}
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
}).listen(8080);
6. Working with Filesystems
Reading Files:
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
Writing Files:
fs.writeFile('example.txt', 'Hello, World!', (err) => {
if (err) throw err;
console.log('File written successfully');
});
Streams: Efficient for handling large files or data streams.
const readStream = fs.createReadStream('example.txt');
readStream.on('data', (chunk) => {
console.log(chunk.toString());
});
7. Asynchronous Programming in NodeJS
Callbacks: Traditional method in NodeJS.
fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data.toString());
});
Promises: More modern approach.
const util = require('util');
const readFile = util.promisify(fs.readFile);
readFile('file.txt', 'utf8')
.then(data => console.log(data))
.catch(err => console.error(err));
async/await: Simplifies promise handling.
async function readFileAsync() {
try {
const data = await readFile('file.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
readFileAsync();
8. Introduction to APIs
A REST API (Representational State Transfer Application Programming Interface) is a
set of rules and conventions for building and interacting with web services. It is based
on the principles of REST, an architectural style for designing networked applications.
REST APIs are widely used for enabling communication between clients (e.g., web
browsers, mobile apps) and servers over the internet.
Basic REST API: Using HTTP methods for CRUD operations.
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const q = url.parse(req.url, true).query;
const txt = q.year + " " + q.month;
res.end(txt);
});
server.listen(8080, () => {
console.log('Server running on port 8080');
});
Module 7: ExpressJS (NodeJS Framework)
1. Introduction to Express
Express: A Nodejs framework that simplifies server creation, routing, and middleware
handling.
2. Setting Up an Express Project
npm install express
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
3. Routing in Express
app.get('/api', (req, res) => {
res.json({ message: 'Hello from API!' });
});
app.post('/api', (req, res) => {
res.json({ message: 'Data received!' });
});
4. Middleware Functions in Express
In Node.js Express, middleware refers to functions that have access to the request
object (req), the response object (res), and the next function in the application's
request-response cycle. Middleware functions can perform tasks such as modifying
request/response objects, executing code, ending the request-response cycle, or calling
the next middleware in the stack
Types of Middleware
1. Application level middleware
2. Router-Level Middleware
3. Route-Specific Middleware
4. Error-Handling Middleware:
5. Third-Party Middleware:
Built-in Middleware in Express
Express provides some built-in middleware functions:
express.json(): Parses incoming requests with JSON payloads.
express.urlencoded(): Parses incoming requests with URL-encoded payloads.
express.static(): Serves static files (e.g., images, CSS, JavaScript).
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
app.use(express.static('public')); // Serve static files from 'public' directory
5. Handling Forms and Data
app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing
application/x-www-form-urlencoded
app.post('/form', (req, res) => {
const name = req.body.name;
res.send(`Hello, ${name}!`);
});
6. Building RESTful APIs with Express
const users = [];
// GET all users
app.get('/users', (req, res) => {
res.json(users);
});
// POST a new user
app.post('/users', (req, res) => {
users.push(req.body);
res.status(201).send('User added to the database');
});
// GET a specific user
app.get('/users/:id', (req, res) => {
const id = req.params.id;
const user = users.find(u => u.id === id);
if (user) {
res.json(user);
} else {
res.status(404).send('User not found');
}
});
SETTING UP MYSQL WITH NODEJS EXPRESS
Install Express and MySQL:
Install the necessary packages:
npm install express mysql
Create a db.js file to handle the database connection:
const mysql = require('mysql');
// Create a connection pool
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'yourpassword',
database: 'mydatabase',
port: “databse port”
});
// Export the pool for use in other files
module.exports = pool