About Lesson
1. Asynchronous & Non-Blocking
- Unlike traditional server-side programming languages, Node.js does not wait for a task to finish before executing the next one.
- Example:
const fs = require(‘fs’);
fs.readFile(‘file.txt’, ‘utf8’, (err, data) => {
if (err) throw err;
console.log(data);
});
console.log(‘Reading file…’);
Output (Order may vary):
Reading file…
(file content)
2. Single-Threaded but Highly Scalable
- Uses an event loop instead of creating multiple threads.
- Can handle thousands of requests without creating separate threads for each.
3. Event-Driven Architecture
- Uses the EventEmitter class to handle events asynchronously.
- Example:
const EventEmitter = require(‘events’);
const event = new EventEmitter();
event.on(‘greet’, () => {
console.log(‘Hello, Event-Driven Programming!’);
});
event.emit(‘greet’);
Output: Hello, Event-Driven Programming!
4. Built-in Modules
- Node.js provides various built-in modules:
Module | Description |
fs | File system operations (read, write, delete files) |
http | Create web servers |
path | Work with file paths |
events | Handle event-driven programming |
os | Get system information |
Creating a Simple HTTP Server
Using Node.js, you can create a basic web server without needing Apache or Nginx.
Example:
JavaScript
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
How to Run:
- Save this as server.js
- Run: node server.js
- Open your browser and visit:
http://localhost:3000
You will see “Hello, World!” displayed.