Node.
js Full Notes
1. Concepts of Node.js
- Node.js is a runtime environment that allows JavaScript to run outside of a browser.
- It uses Google Chrome's V8 engine.
- It is designed for building scalable and fast network applications.
- It supports non-blocking (asynchronous) I/O operations.
2. Features of Node.js
- Asynchronous & Event-Driven
- Fast Execution using V8 engine
- Single-threaded but scalable
- Cross-platform
- No buffering (outputs data in chunks)
- Large NPM (Node Package Manager) support
- Built-in modules
3. Downloading & Installing Node.js (Windows)
- Visit https://nodejs.org
- Download the LTS version for Windows.
- Run the installer.
- After installation, verify: node -v, npm -v
4. Setting Up Node.js Server (HTTP Server)
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello, World!');
res.end();
}).listen(3000);
5. Components Required
- Node.js installed
- Built-in modules like http, fs, url
- Text editor (like VS Code)
- Terminal (CMD/PowerShell)
6. Required Modules
- Core Modules: Provided by Node.js (http, fs, url, etc.)
- Local Modules: Created by user
- Third-party Modules: Installed via npm
7. Built-in Modules
- http: Create server and handle HTTP requests
- fs: File system operations
- url: URL parsing
- path: File path manipulation
- events: Event handling
8. require() Function
- Used to import modules:
const fs = require('fs');
- For user-defined module:
const myModule = require('./myModule.js');
9. User-Defined Modules
math.js:
exports.add = (a, b) => a + b;
app.js:
const math = require('./math');
console.log(math.add(10, 5));
10. HTTP Module
const http = require('http');
11. Node.js as a Web Server
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>Hello, Web</h1>');
res.end();
}).listen(3000);
12. Reading Query String
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const q = url.parse(req.url, true).query;
const name = q.name;
res.write(`Hello ${name}`);
res.end();
}).listen(3000);
13. Splitting Query String
const q = url.parse(req.url, true).query;
const fullName = q.name.split(" ");
14. File System Module (fs)
Read Files: fs.readFile()
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
Create Files
- fs.appendFile(): fs.appendFile('file.txt', 'Hello content!', err => {});
- fs.open(): fs.open('file.txt', 'w', (err, file) => {});
- fs.writeFile(): fs.writeFile('file.txt', 'Hello', err => {});
Update Files
- Use appendFile() to add content
- Use writeFile() to replace content
Delete Files: fs.unlink()
fs.unlink('file.txt', err => {});
Rename Files: fs.rename()
fs.rename('old.txt', 'new.txt', err => {});