Node.js Basics Definition: A JavaScript runtime built on Chrome's V8 JavaScript engine. Purpose: Used for building scalable network applications. Non-blocking I/O: Uses an event-driven, non-blocking I/O model. Installation: Download from nodejs.org or use a version manager like nvm . Running a file: node your_file.js Global Objects global : Global namespace object (similar to window in browsers). process : Provides information about, and control over, the current Node.js process. process.argv : Array of command line arguments. process.env : Object containing user environment. process.cwd() : Current working directory. process.exit(code) : Exits the process. __dirname : Absolute path to the directory of the current module. __filename : Absolute path to the file of the current module. module : Reference to the current module. exports : A reference to module.exports , used to export objects. require() : Function to import modules. Modules CommonJS Module System Exporting: // myModule.js module.exports = { add: (a, b) => a + b, subtract: (a, b) => a - b }; // Or individually: exports.multiply = (a, b) => a * b; Importing: // app.js const myModule = require('./myModule'); console.log(myModule.add(5, 3)); // 8 const { multiply } = require('./myModule'); console.log(multiply(5, 3)); // 15 Event Loop Concept: Handles asynchronous operations in Node.js. Phases: Timers: setTimeout() , setInterval() Pending Callbacks: I/O callbacks deferred to the next loop iteration. Idle, Prepare: Internal only. Poll: Retrieve new I/O events; execute I/O related callbacks. Check: setImmediate() callbacks. Close Callbacks: 'close' event callbacks. Microtask Queue: process.nextTick() and Promises ( .then() / .catch() / await ) run between phases. nextTick has higher priority than Promises. Asynchronous Programming Callbacks Traditional way to handle async operations. Can lead to "Callback Hell" for complex nested operations. fs.readFile('file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); }); Promises Represents the eventual completion (or failure) of an asynchronous operation. States: pending , fulfilled , rejected . const myPromise = new Promise((resolve, reject) => { // async operation if (success) { resolve('Data fetched'); } else { reject('Error fetching data'); } }); myPromise .then(data => console.log(data)) .catch(error => console.error(error)); Async/Await Syntactic sugar built on Promises, making async code look synchronous. Must be used inside an async function. async function fetchData() { try { const data = await myPromise; console.log(data); } catch (error) { console.error(error); } } fetchData(); Core Modules (Examples) fs (File System) Read File: const fs = require('fs'); fs.readFile('path/to/file.txt', 'utf8', (err, data) => { /* ... */ }); // Async const data = fs.readFileSync('path/to/file.txt', 'utf8'); // Sync Write File: fs.writeFile('path/to/file.txt', 'Hello Node!', (err) => { /* ... */ }); // Async fs.writeFileSync('path/to/file.txt', 'Hello Node!'); // Sync Append File: fs.appendFile() , fs.appendFileSync() Delete File: fs.unlink() , fs.unlinkSync() Check if exists: fs.existsSync() http (HTTP Server/Client) Create Server: const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World\\n'); }); server.listen(3000, '127.0.0.1', () => { console.log('Server running at http://127.0.0.1:3000/'); }); HTTP Request (Client): const http = require('http'); http.get('http://example.com', (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log(data); }); }).on('error', (err) => { console.error(err); }); path (Path Utilities) path.join(__dirname, 'views', 'index.html') path.resolve('foo', 'bar', '../baz') path.basename('/foo/bar/baz.txt') $\rightarrow$ 'baz.txt' path.extname('index.html') $\rightarrow$ '.html' events (Event Emitters) Concept: Core of Node.js event-driven architecture. Usage: const EventEmitter = require('events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', () => { console.log('an event occurred!'); }); myEmitter.emit('event'); npm (Node Package Manager) Initialize project: npm init Install package: npm install [package-name] (shorthand: npm i ) Install dev dependency: npm i [package-name] --save-dev or -D Uninstall package: npm uninstall [package-name] Run script: npm run [script-name] (e.g., npm run start ) Global install: npm i -g [package-name] (e.g., npm i -g nodemon ) package.json : Defines project metadata and dependencies. package-lock.json : Records exact versions of dependencies. Error Handling Synchronous: Use try...catch blocks. Asynchronous (Callbacks): First argument of callback is usually err . Asynchronous (Promises): Use .catch() or try...catch with await . Event Emitters: Listen for 'error' events. If no listener, process terminates. Unhandled Rejection: process.on('unhandledRejection', (reason, promise) => { ... }); Uncaught Exception: process.on('uncaughtException', (err) => { ... }); Streams Concept: Abstract interface for working with streaming data. Types: Readable : For reading data (e.g., fs.createReadStream() ). Writable : For writing data (e.g., fs.createWriteStream() ). Duplex : Both Readable and Writable (e.g., net.Socket ). Transform : Duplex streams that can modify data as it's written/read (e.g., zlib.Gzip ). Piping: Connects the output of one stream to the input of another. readableStream.pipe(writableStream); Debugging Node.js Inspector: node --inspect your_file.js Open Chrome DevTools ( chrome://inspect ) to connect. Can use debugger; keyword in code to set breakpoints. Security Best Practices Input Validation: Always validate user input. Dependency Auditing: Use npm audit to check for vulnerabilities. Environment Variables: Store sensitive data (API keys, passwords) in environment variables, not in code. Rate Limiting: Protect against brute-force attacks. CORS: Properly configure Cross-Origin Resource Sharing. SQL Injection/XSS: Use parameterized queries and sanitize output.