Node.js and Express.
js - Beginner Notes
1. What is Node.js?
Node.js is a runtime environment that allows you to run JavaScript code outside the browser. It
is built on the V8 JavaScript engine (the same engine that powers Google Chrome).
With Node.js, you can use JavaScript to build backend servers, APIs, work with files, connect to
databases, and more.
2. Why Use Node.js?
- Allows full-stack development using JavaScript
- Fast and scalable due to non-blocking I/O
- Has a large ecosystem of packages via npm
- Suitable for real-time apps like chat and live notifications
3. What Can Node.js Do?
- Create web servers
- Handle HTTP requests and responses
- Read and write files
- Work with databases
- Use third-party packages like Express, bcrypt, etc.
4. Simple Node.js Server Example
const http = require('http');
const server = http.createServer((req, res) => {
res.write('Hello from Node.js!');
res.end();
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
5. What is Express.js?
Express.js is a web application framework for Node.js. It simplifies the process of building web
servers and APIs.
It provides built-in functions for routing, middleware support, and handling HTTP requests and
responses.
6. Why Use Express.js?
- Cleaner and simpler routing system
- Easily handle different HTTP methods (GET, POST, etc.)
- Middleware support for additional features
- Scalable structure for large applications
7. Simple Express Server Example
const express = require('express');
const app = express();
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
8. Express.js vs Node.js (Raw)
- Node.js gives you low-level tools to build servers.
- Express.js is built on top of Node.js and provides a higher-level structure to make coding faster
and easier.
- Without Express, you'd need to write a lot more code to handle routing and request parsing.