Node.js Basics β
What is Node.js?
- A JavaScript runtime built on Chromeβs V8 engine.
- Used for server-side scripting and to build fast, scalable network applications.
- Asynchronous, event-driven, non-blocking I/O.
Node.js Modules:
- Built-in modules like
fs
,http
,path
, etc. - CommonJS module system: Use
require
to load modules.
jsconst fs = require("fs");
- Built-in modules like
npm (Node Package Manager):
- Manages Node.js packages.
- Install packages:bash
npm install express
Global Objects:
__dirname
: Directory path of the current file.__filename
: Filename of the current file.console
: For logging.setTimeout
,setInterval
: Timers.
Modules & Exports β
Creating a Module:
- Split your code into reusable modules.
js// myModule.js module.exports = function () { console.log("Hello from module"); };
Loading a Module:
- Use
require
to include the module in other files.
jsconst myModule = require("./myModule"); myModule();
- Use
File System (fs) Module β
Reading Files:
- Asynchronous file read:js
const fs = require("fs"); fs.readFile("file.txt", "utf8", (err, data) => { if (err) throw err; console.log(data); });
- Asynchronous file read:
Writing Files:
- Asynchronous file write:js
fs.writeFile("file.txt", "Hello World", (err) => { if (err) throw err; console.log("File written"); });
- Asynchronous file write:
Sync Methods:
- Blocking methods that pause execution until completed.
jsconst data = fs.readFileSync("file.txt", "utf8"); console.log(data);
HTTP Module β
Creating a Server:
- Use the
http
module to create a web server.
jsconst http = require("http"); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader("Content-Type", "text/plain"); res.end("Hello World"); }); server.listen(3000, () => { console.log("Server running on port 3000"); });
- Use the
Handling Requests and Responses:
- Request methods like
GET
,POST
can be handled by checkingreq.method
. - Handle routing using
req.url
.
- Request methods like
Express.js Framework β
What is Express.js?
- Fast, unopinionated web framework for Node.js.
- Simplifies routing, middleware, and handling requests/responses.
Basic Express Server:
jsconst express = require("express"); const app = express(); app.get("/", (req, res) => { res.send("Hello World"); }); app.listen(3000, () => { console.log("Server running on port 3000"); });
Routing in Express:
- Define routes for different HTTP methods.
jsapp.get("/about", (req, res) => { res.send("About Page"); });
Middleware:
- Functions that execute in the request-response cycle.
jsapp.use((req, res, next) => { console.log("Middleware running"); next(); });
Serving Static Files:
- Use
express.static
to serve static assets like HTML, CSS, JS.
jsapp.use(express.static("public"));
- Use
Database Integration β
MongoDB with Mongoose:
- MongoDB is a NoSQL database.
- Mongoose is an ODM (Object Data Modeling) library for MongoDB.
Connecting to MongoDB:
jsconst mongoose = require("mongoose"); mongoose.connect("mongodb://localhost/mydb", { useNewUrlParser: true, useUnifiedTopology: true, });
Creating Schemas and Models:
jsconst userSchema = new mongoose.Schema({ name: String, age: Number, }); const User = mongoose.model("User", userSchema);
Performing CRUD Operations:
- Create:js
const newUser = new User({ name: "John", age: 30 }); newUser.save();
- Read:js
User.find({}, (err, users) => { console.log(users); });
- Update:js
User.updateOne({ name: "John" }, { age: 31 }, (err) => { console.log("Updated"); });
- Delete:js
User.deleteOne({ name: "John" }, (err) => { console.log("Deleted"); });
- Create:
Asynchronous Programming β
Callbacks:
- Functions passed as arguments to be executed later.
jsfs.readFile("file.txt", "utf8", (err, data) => { if (err) throw err; console.log(data); });
Promises:
- Cleaner alternative to callbacks, using
.then()
and.catch()
.
jsconst myPromise = new Promise((resolve, reject) => { if (success) { resolve("Success!"); } else { reject("Error!"); } }); myPromise .then((result) => console.log(result)) .catch((err) => console.log(err));
- Cleaner alternative to callbacks, using
Async/Await:
- Syntactic sugar over Promises for writing asynchronous code in a synchronous style.
jsasync function fetchData() { try { const data = await fs.promises.readFile("file.txt", "utf8"); console.log(data); } catch (err) { console.log(err); } }
Error Handling β
Try/Catch Block:
- Handle synchronous code errors.
jstry { const data = fs.readFileSync("file.txt", "utf8"); } catch (err) { console.log("Error:", err); }
Error Handling in Async Code:
- Catch errors in async code with Promises or
try/catch
in async functions.
jsmyPromise.catch((err) => console.log(err));
- Catch errors in async code with Promises or
Streams β
Readable and Writable Streams:
- Used to handle large amounts of data efficiently (e.g., file reading/writing).
jsconst readableStream = fs.createReadStream("input.txt"); const writableStream = fs.createWriteStream("output.txt"); readableStream.pipe(writableStream); // Copies data from input.txt to output.txt
EventEmitter β
Creating Events:
- Node.js is event-driven, and the
EventEmitter
module allows defining and triggering custom events.
jsconst EventEmitter = require("events"); const eventEmitter = new EventEmitter(); eventEmitter.on("myEvent", () => { console.log("Event triggered"); }); eventEmitter.emit("myEvent");
- Node.js is event-driven, and the
Environment Variables β
- Using Environment Variables:
- Load configuration settings (e.g., API keys) from environment variables.
bashexport PORT=3000
- Access in Node.js:
jsconst port = process.env.PORT || 3000;
Deployment β
Hosting a Node.js App:
- Deploy Node.js apps on platforms like Heroku, AWS, or DigitalOcean.
Process Management with PM2:
- PM2 is used to manage and keep your Node.js apps running.
bashnpm install pm2 -g pm2 start app.js
Security Practices β
Input Validation:
- Always validate user inputs to prevent attacks like SQL Injection.
Use HTTPS:
- Ensure secure data transmission using HTTPS in production.
Helmet:
- Middleware that adds security headers to protect from common attacks.
bashnpm install helmet
jsconst helmet = require("helmet"); app.use(helmet());
**Summary ** β
- Non-blocking, asynchronous I/O: Efficient for handling multiple requests.
- CommonJS Modules: Modular approach to code with
require
andmodule.exports
. - File System: Interact with files using
fs
. - Express.js: Simplifies routing, middleware, and server-side logic.
- Asynchronous programming: Callbacks, Promises,
async/await
. - Database Integration: Use MongoDB with Mongoose for CRUD operations.
- Streams: Handle large data using streams for efficient I/O.
- Error Handling: Use
try/catch
or.catch()
for async code errors.