├── Node Js Fundamentals ├── 10 Testing │ ├── db.js │ ├── mathUtils.js │ ├── 02 Integration Testing │ │ └── app.integration.test.js │ ├── 05 Code Coverage │ │ └── codeCoverage.test.js │ ├── app.js │ ├── 01 Unit Testing with Jest │ │ └── mathUtils.test.js │ ├── 03 Mocking Dependencies │ │ └── mathUtils.mock.test.js │ ├── 06 End-to-End Testing │ │ └── e2e.test.js │ └── 04 API Testing with Supertest │ │ └── app.api.test.js ├── 06 Express.js Framework │ ├── 04 Template Engines (EJS Pug) │ │ ├── example-template.ejs.txt │ │ └── TemplateEngines.js │ ├── 01 Setting Up Express │ │ └── SetupExpress.js │ ├── 05 Error Handling │ │ └── ErrorHandling.js │ ├── 02 Routing and Middleware │ │ └── RoutingMiddleware.js │ ├── 03 Request and Response Objects │ │ └── RequestResponseObjects.js │ ├── 06 REST API Development │ │ └── RestAPI.js │ └── index.html ├── 11 Deployment and DevOps │ ├── app.js │ ├── 03 Dockerizing Node.js Apps │ │ └── Dockerfile.txt │ ├── 01 Environment Variables │ │ └── envConfig.js │ ├── 04 CI CD Pipelines │ │ └── github-actions.yaml │ ├── 05 Cloud Deployment (AWS Heroku Vercel) │ │ └── README.md │ ├── 02 PM2 for Process Management │ │ └── pm2Config.js │ ├── 06 Logging and Monitoring │ │ └── loggingMonitoring.js │ └── index.html ├── 02 Modules and Packages │ ├── 04 Creating and Publishing NPM Packages │ │ ├── MyPackage.js │ │ └── README.md │ ├── 05 Package.json and Dependency Management │ │ └── package.json │ ├── 01 CommonJS Modules │ │ └── CommonJSModules.js │ ├── 02 ES Modules │ │ └── ESModules.js │ ├── 03 require vs import │ │ └── RequireVsImport.js │ └── index.html ├── 01 Node.js Basics │ ├── 01 Understanding the Node.js Runtime │ │ └── NodeRuntime.js │ ├── 03 V8 Engine │ │ └── V8Engine.js │ ├── 02 Event Loop and Non-Blocking IO │ │ └── EventLoop.js │ ├── 04 Global Objects (process buffer console) │ │ └── GlobalObjects.js │ ├── 05 Node.js CLI and REPL │ │ └── NodeCLI.js │ └── index.html ├── 04 File System │ ├── 04 File System Watchers │ │ └── FileSystemWatchers.js │ ├── 01 Reading and Writing Files (fs module) │ │ └── ReadWriteFiles.js │ ├── 03 Streams and Buffers │ │ └── StreamsAndBuffers.js │ ├── 05 Directory Management │ │ └── DirectoryManagement.js │ ├── 02 Synchronous vs Asynchronous Methods │ │ └── SyncVsAsync.js │ └── index.html ├── 03 Asynchronous Programming │ ├── 04 Event Emitters │ │ └── EventEmitters.js │ ├── 01 Callbacks │ │ └── Callbacks.js │ ├── 03 Async Await │ │ └── AsyncAwait.js │ ├── 02 Promises │ │ └── Promises.js │ ├── 05 Handling Asynchronous Errors │ │ └── AsyncErrors.js │ └── index.html ├── 05 HTTP and Networking │ ├── 01 Creating HTTP Servers (http module) │ │ └── HTTPServer.js │ ├── 03 URL Parsing │ │ └── URLParsing.js │ ├── 04 TCP UDP Servers (net module) │ │ └── TCPServer.js │ ├── 05 WebSockets with ws │ │ └── WebSocketServer.js │ ├── 02 Handling Requests and Responses │ │ └── RequestResponse.js │ └── index.html ├── 07 Databases │ ├── 05 Database Migrations │ │ ├── example-migration.js │ │ └── SequelizeMigrations.js │ ├── 01 MongoDB with Mongoose │ │ └── MongoDBWithMongoose.js │ ├── 03 Connection Pooling │ │ └── ConnectionPooling.js │ ├── 02 SQL Databases with Sequelize Knex │ │ └── SequelizeSetup.js │ ├── 06 NoSQL vs SQL Trade-offs │ │ └── README.md │ ├── 04 CRUD Operations │ │ └── CRUDOperations.js │ └── index.html ├── 08 Authentication and Security │ ├── 05 Securing APIs (CORS Helmet) │ │ └── SecureAPI.js │ ├── 02 Password Hashing with bcrypt │ │ └── PasswordHashing.js │ ├── 06 Input Validation and Sanitization │ │ └── InputValidation.js │ ├── 01 JWT and OAuth │ │ └── JWTAuth.js │ ├── 03 Session Management │ │ └── SessionManagement.js │ ├── 04 Middleware for Authentication │ │ └── AuthMiddleware.js │ └── index.html └── 09 Performance Optimization │ ├── 04 Rate Limiting │ └── RateLimiting.js │ ├── 01 Clustering with cluster Module │ └── Clustering.js │ ├── 06 Profiling and Debugging │ └── ProfilingDebugging.js │ ├── 02 Load Balancing │ └── LoadBalancing.js │ ├── 05 Optimizing Event Loop │ └── OptimizeEventLoop.js │ ├── 03 Caching with Redis │ └── RedisCaching.js │ └── index.html ├── LICENSE ├── README.md └── Node Js Interview Questions └── README.md /Node Js Fundamentals/10 Testing/db.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | getUser: (id) => { 3 | return new Promise(resolve => { 4 | setTimeout(() => resolve({ id, name: `User${id}` }), 500); 5 | }); 6 | } 7 | }; -------------------------------------------------------------------------------- /Node Js Fundamentals/10 Testing/mathUtils.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | add: (a, b) => a + b, 3 | subtract: (a, b) => a - b, 4 | fetchData: () => { 5 | return new Promise(resolve => { 6 | setTimeout(() => resolve('Data from external service'), 1000); 7 | }); 8 | } 9 | }; -------------------------------------------------------------------------------- /Node Js Fundamentals/06 Express.js Framework/04 Template Engines (EJS Pug)/example-template.ejs.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | <%= title %> 7 | 8 | 9 |

<%= title %>

10 |

<%= message %>

11 | 12 | -------------------------------------------------------------------------------- /Node Js Fundamentals/11 Deployment and DevOps/app.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | app.use(express.json()); 5 | 6 | app.get('/', (req, res) => { 7 | res.json({ message: 'Hello from Node.js app!' }); 8 | }); 9 | 10 | const PORT = process.env.PORT || 3000; 11 | app.listen(PORT, () => { 12 | console.log(`Server running on port ${PORT}`); 13 | }); 14 | 15 | module.exports = app; -------------------------------------------------------------------------------- /Node Js Fundamentals/02 Modules and Packages/04 Creating and Publishing NPM Packages/MyPackage.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Creating an NPM Package 2 | // This file represents the main code for a simple NPM package. 3 | 4 | // A simple utility function to publish as an NPM package 5 | const capitalize = (str) => { 6 | if (typeof str !== 'string') throw new Error('Input must be a string'); 7 | return str.charAt(0).toUpperCase() + str.slice(1); 8 | }; 9 | 10 | // Export the function 11 | module.exports = { capitalize }; 12 | 13 | // This file would be part of an NPM package. See the README.md for publishing instructions. -------------------------------------------------------------------------------- /Node Js Fundamentals/02 Modules and Packages/05 Package.json and Dependency Management/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-modules-demo", 3 | "version": "1.0.0", 4 | "description": "A demo project for Node.js modules and packages", 5 | "main": "index.js", 6 | "type": "module", 7 | "scripts": { 8 | "start": "node index.js", 9 | "test": "echo \"Error: no test specified\" && exit 1" 10 | }, 11 | "dependencies": { 12 | "lodash": "^4.17.21" 13 | }, 14 | "devDependencies": { 15 | "nodemon": "^3.0.0" 16 | }, 17 | "author": "Your Name", 18 | "license": "MIT" 19 | } -------------------------------------------------------------------------------- /Node Js Fundamentals/01 Node.js Basics/01 Understanding the Node.js Runtime/NodeRuntime.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Understanding the Node.js Runtime 2 | // Node.js is a JavaScript runtime built on Chrome's V8 engine, enabling server-side JavaScript execution. 3 | 4 | // Log Node.js version and runtime information 5 | console.log('Node.js Version:', process.version); 6 | console.log('Platform:', process.platform); 7 | console.log('Architecture:', process.arch); 8 | console.log('Process ID:', process.pid); 9 | 10 | // To run this file in a Node.js environment: 11 | // 1. Save this file as NodeRuntime.js 12 | // 2. Open a terminal and navigate to the file's directory 13 | // 3. Run: node NodeRuntime.js -------------------------------------------------------------------------------- /Node Js Fundamentals/01 Node.js Basics/03 V8 Engine/V8Engine.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: V8 Engine 2 | // The V8 engine is Google's JavaScript engine that powers Node.js, compiling JavaScript to machine code. 3 | 4 | // Perform a simple computation to demonstrate V8's efficiency 5 | const start = Date.now(); 6 | let sum = 0; 7 | for (let i = 0; i < 1e7; i++) { 8 | sum += i; 9 | } 10 | const end = Date.now(); 11 | console.log('Sum:', sum); 12 | console.log('Time taken (ms):', end - start); 13 | 14 | // Log V8 version (available via process.versions) 15 | console.log('V8 Version:', process.versions.v8); 16 | 17 | // To run this file in a Node.js environment: 18 | // 1. Save this file as V8Engine.js 19 | // 2. Open a terminal and navigate to the file's directory 20 | // 3. Run: node V8Engine.js -------------------------------------------------------------------------------- /Node Js Fundamentals/10 Testing/02 Integration Testing/app.integration.test.js: -------------------------------------------------------------------------------- 1 | const request = require('supertest'); 2 | const app = require('./app'); 3 | 4 | describe('Integration Test: Users API', () => { 5 | test('should fetch a user by ID', async () => { 6 | const res = await request(app) 7 | .get('/users/1') 8 | .expect(200); 9 | 10 | expect(res.body).toEqual({ id: 1, name: 'User1' }); 11 | }); 12 | }); 13 | 14 | // To run this in a Node.js environment: 15 | // 1. Initialize a project: npm init -y 16 | // 2. Install dependencies: npm install express supertest jest --save-dev 17 | // 3. Save this file as app.integration.test.js 18 | // 4. Save app.js and db.js in the same directory 19 | // 5. Run: npx jest app.integration.test.js 20 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/10 Testing/05 Code Coverage/codeCoverage.test.js: -------------------------------------------------------------------------------- 1 | const mathUtils = require('./mathUtils'); 2 | 3 | describe('Code Coverage Test', () => { 4 | test('should test add function', () => { 5 | expect(mathUtils.add(1, 2)).toBe(3); 6 | }); 7 | 8 | // Note: subtract and fetchData are not tested to demonstrate coverage gaps 9 | }); 10 | 11 | // To run this in a Node.js environment: 12 | // 1. Initialize a project: npm init -y 13 | // 2. Install Jest: npm install --save-dev jest 14 | // 3. Save this file as codeCoverage.test.js 15 | // 4. Save mathUtils.js in the same directory 16 | // 5. Create a package.json script: "test:coverage": "jest --coverage" 17 | // 6. Run: npm run test:coverage 18 | // 7. Check the coverage report in the generated coverage/ directory 19 | // Note: This code won't execute here due to runtime restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/10 Testing/app.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const db = require('./db'); 3 | const app = express(); 4 | 5 | app.use(express.json()); 6 | 7 | app.get('/users/:id', async (req, res) => { 8 | const user = await db.getUser(parseInt(req.params.id)); 9 | res.json(user); 10 | }); 11 | 12 | app.post('/users', (req, res) => { 13 | const user = req.body; 14 | res.status(201).json({ message: 'User created', user }); 15 | }); 16 | 17 | module.exports = app; 18 | 19 | // To run this app in a Node.js environment: 20 | // 1. Initialize a project: npm init -y 21 | // 2. Install Express: npm install express 22 | // 3. Save this file as app.js 23 | // 4. Create a start script: node -e "require('./app').listen(3000, () => console.log('Server running'))" 24 | // Note: This app is meant for testing and won't run here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/10 Testing/01 Unit Testing with Jest/mathUtils.test.js: -------------------------------------------------------------------------------- 1 | const mathUtils = require('./mathUtils'); 2 | 3 | describe('MathUtils', () => { 4 | test('should add two numbers correctly', () => { 5 | expect(mathUtils.add(2, 3)).toBe(5); 6 | expect(mathUtils.add(-1, 1)).toBe(0); 7 | }); 8 | 9 | test('should subtract two numbers correctly', () => { 10 | expect(mathUtils.subtract(5, 3)).toBe(2); 11 | expect(mathUtils.subtract(1, -1)).toBe(2); 12 | }); 13 | }); 14 | 15 | // To run this in a Node.js environment: 16 | // 1. Initialize a project: npm init -y 17 | // 2. Install Jest: npm install --save-dev jest 18 | // 3. Save this file as mathUtils.test.js 19 | // 4. Save the mathUtils.js file in the same directory 20 | // 5. Run: npx jest mathUtils.test.js 21 | // Note: This code won't execute here due to runtime restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/04 File System/04 File System Watchers/FileSystemWatchers.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: File System Watchers 2 | // File system watchers monitor files or directories for changes. 3 | 4 | const fs = require('fs'); 5 | 6 | // Watch a file for changes 7 | fs.watch('watch-me.txt', (eventType, filename) => { 8 | if (filename) { 9 | console.log(`File ${filename} changed! Event: ${eventType}`); 10 | } 11 | }); 12 | 13 | console.log('Watching for changes to watch-me.txt...'); 14 | 15 | // To use this in a real Node.js environment: 16 | // 1. Create a file named watch-me.txt 17 | // 2. Save this file as FileSystemWatchers.js 18 | // 3. Open a terminal and navigate to the file's directory 19 | // 4. Run: node FileSystemWatchers.js 20 | // 5. Modify watch-me.txt (e.g., edit and save it) to see the watcher in action 21 | // Note: This code won't execute here due to file I/O restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/01 Node.js Basics/02 Event Loop and Non-Blocking IO/EventLoop.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Event Loop and Non-Blocking I/O 2 | // Node.js uses an event loop to handle asynchronous operations, enabling non-blocking I/O. 3 | 4 | // Demonstrate non-blocking behavior with setTimeout 5 | console.log('Start'); 6 | 7 | setTimeout(() => { 8 | console.log('This runs after 2 seconds'); 9 | }, 2000); 10 | 11 | setImmediate(() => { 12 | console.log('This runs in the next event loop iteration'); 13 | }); 14 | 15 | console.log('End'); 16 | 17 | // In a real Node.js environment, the output order would be: 18 | // 1. Start 19 | // 2. End 20 | // 3. This runs in the next event loop iteration 21 | // 4. This runs after 2 seconds 22 | 23 | // To run this file in a Node.js environment: 24 | // 1. Save this file as EventLoop.js 25 | // 2. Open a terminal and navigate to the file's directory 26 | // 3. Run: node EventLoop.js -------------------------------------------------------------------------------- /Node Js Fundamentals/03 Asynchronous Programming/04 Event Emitters/EventEmitters.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Event Emitters 2 | // Event Emitters allow you to create and handle custom events in Node.js. 3 | 4 | // Import the events module 5 | const EventEmitter = require('events'); 6 | 7 | // Create an instance of EventEmitter 8 | const myEmitter = new EventEmitter(); 9 | 10 | // Define an event listener 11 | myEmitter.on('myEvent', (data) => { 12 | console.log('Event Triggered:', data); 13 | }); 14 | 15 | // Emit the event 16 | console.log('Start'); 17 | myEmitter.emit('myEvent', 'Hello from Event Emitter!'); 18 | console.log('End'); 19 | 20 | // Expected Output: 21 | // Start 22 | // Event Triggered: Hello from Event Emitter! 23 | // End 24 | 25 | // To run this in a Node.js environment: 26 | // 1. Save this file as EventEmitters.js 27 | // 2. Open a terminal and navigate to the file's directory 28 | // 3. Run: node EventEmitters.js -------------------------------------------------------------------------------- /Node Js Fundamentals/05 HTTP and Networking/01 Creating HTTP Servers (http module)/HTTPServer.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Creating HTTP Servers (http module) 2 | // The http module allows you to create HTTP servers in Node.js. 3 | 4 | const http = require('http'); 5 | 6 | // Create an HTTP server 7 | const server = http.createServer((req, res) => { 8 | res.writeHead(200, { 'Content-Type': 'text/plain' }); 9 | res.end('Hello from Node.js HTTP Server!\n'); 10 | }); 11 | 12 | // Listen on port 3000 13 | server.listen(3000, () => { 14 | console.log('Server running at http://localhost:3000/'); 15 | }); 16 | 17 | // To run this in a Node.js environment: 18 | // 1. Save this file as HTTPServer.js 19 | // 2. Open a terminal and navigate to the file's directory 20 | // 3. Run: node HTTPServer.js 21 | // 4. Open a browser or use curl to visit: http://localhost:3000/ 22 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/02 Modules and Packages/01 CommonJS Modules/CommonJSModules.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: CommonJS Modules 2 | // CommonJS is the default module system in Node.js, using module.exports and require. 3 | 4 | // Exporting a module (imagine this as a separate file, e.g., math.js) 5 | const add = (a, b) => a + b; 6 | const subtract = (a, b) => a - b; 7 | module.exports = { add, subtract }; 8 | 9 | // Importing the module (in a real setup, this would be in a separate file) 10 | // const math = require('./math.js'); 11 | const math = { add, subtract }; // Simulated for this demo 12 | 13 | console.log('Add:', math.add(5, 3)); // 8 14 | console.log('Subtract:', math.subtract(5, 3)); // 2 15 | 16 | // To run this in a Node.js environment: 17 | // 1. Create a file math.js with the exports (lines 6-8) 18 | // 2. Create a main file, e.g., CommonJSModules.js, with the require and usage (lines 11-14) 19 | // 3. Run: node CommonJSModules.js -------------------------------------------------------------------------------- /Node Js Fundamentals/06 Express.js Framework/01 Setting Up Express/SetupExpress.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Setting Up Express 2 | // Express is a minimal web framework for Node.js to build servers. 3 | 4 | // Note: Requires Express installation (npm install express) 5 | const express = require('express'); 6 | const app = express(); 7 | 8 | // Basic route 9 | app.get('/', (req, res) => { 10 | res.send('Hello from Express!'); 11 | }); 12 | 13 | // Start the server 14 | const PORT = 3000; 15 | app.listen(PORT, () => { 16 | console.log(`Express server running on http://localhost:${PORT}`); 17 | }); 18 | 19 | // To run this in a Node.js environment: 20 | // 1. Initialize a project: npm init -y 21 | // 2. Install Express: npm install express 22 | // 3. Save this file as SetupExpress.js 23 | // 4. Run: node SetupExpress.js 24 | // 5. Visit http://localhost:3000 in a browser 25 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/10 Testing/03 Mocking Dependencies/mathUtils.mock.test.js: -------------------------------------------------------------------------------- 1 | const mathUtils = require('./mathUtils'); 2 | 3 | jest.mock('./mathUtils', () => ({ 4 | ...jest.requireActual('./mathUtils'), 5 | fetchData: jest.fn() 6 | })); 7 | 8 | describe('MathUtils with Mocking', () => { 9 | test('should mock fetchData', async () => { 10 | mathUtils.fetchData.mockResolvedValue('Mocked data'); 11 | const result = await mathUtils.fetchData(); 12 | expect(result).toBe('Mocked data'); 13 | expect(mathUtils.fetchData).toHaveBeenCalled(); 14 | }); 15 | }); 16 | 17 | // To run this in a Node.js environment: 18 | // 1. Initialize a project: npm init -y 19 | // 2. Install Jest: npm install --save-dev jest 20 | // 3. Save this file as mathUtils.mock.test.js 21 | // 4. Save mathUtils.js in the same directory 22 | // 5. Run: npx jest mathUtils.mock.test.js 23 | // Note: This code won't execute here due to runtime restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/01 Node.js Basics/04 Global Objects (process buffer console)/GlobalObjects.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Global Objects (process, buffer, console) 2 | // Node.js provides global objects for interacting with the environment, buffers, and logging. 3 | 4 | // Using process to get environment information 5 | console.log('Current Directory:', process.cwd()); 6 | console.log('Environment Variables:', process.env); 7 | 8 | // Using buffer to handle binary data 9 | const buffer = Buffer.from('Hello, Node.js!'); 10 | console.log('Buffer:', buffer); 11 | console.log('Buffer to String:', buffer.toString()); 12 | 13 | // Using console for logging 14 | console.log('This is a log message'); 15 | console.error('This is an error message'); 16 | console.warn('This is a warning message'); 17 | 18 | // To run this file in a Node.js environment: 19 | // 1. Save this file as GlobalObjects.js 20 | // 2. Open a terminal and navigate to the file's directory 21 | // 3. Run: node GlobalObjects.js -------------------------------------------------------------------------------- /Node Js Fundamentals/02 Modules and Packages/02 ES Modules/ESModules.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: ES Modules 2 | // ES Modules use import/export syntax and are supported in Node.js (requires "type": "module" in package.json). 3 | 4 | // Exporting a module (imagine this as a separate file, e.g., utils.js) 5 | export const multiply = (a, b) => a * b; 6 | export const divide = (a, b) => a / b; 7 | 8 | // Importing the module (in a real setup, this would be in a separate file) 9 | // import { multiply, divide } from './utils.js'; 10 | const utils = { multiply, divide }; // Simulated for this demo 11 | 12 | console.log('Multiply:', utils.multiply(5, 3)); // 15 13 | console.log('Divide:', utils.divide(6, 2)); // 3 14 | 15 | // To run this in a Node.js environment: 16 | // 1. Add "type": "module" to package.json 17 | // 2. Create a file utils.js with the exports (lines 6-7) 18 | // 3. Create a main file, e.g., ESModules.js, with the import and usage (lines 10-13) 19 | // 4. Run: node ESModules.js -------------------------------------------------------------------------------- /Node Js Fundamentals/05 HTTP and Networking/03 URL Parsing/URLParsing.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: URL Parsing 2 | // The url module helps parse and manipulate URLs in Node.js. 3 | 4 | const url = require('url'); 5 | 6 | // Example URL to parse 7 | const myURL = 'http://example.com:8080/path?name=NodeJS&version=18#section'; 8 | 9 | // Parse the URL 10 | const parsedURL = url.parse(myURL, true); 11 | 12 | console.log('Parsed URL Object:', parsedURL); 13 | console.log('Protocol:', parsedURL.protocol); // http: 14 | console.log('Host:', parsedURL.host); // example.com:8080 15 | console.log('Path:', parsedURL.pathname); // /path 16 | console.log('Query Parameters:', parsedURL.query); // { name: 'NodeJS', version: '18' } 17 | console.log('Hash:', parsedURL.hash); // #section 18 | 19 | // To run this in a Node.js environment: 20 | // 1. Save this file as URLParsing.js 21 | // 2. Open a terminal and navigate to the file's directory 22 | // 3. Run: node URLParsing.js 23 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/10 Testing/06 End-to-End Testing/e2e.test.js: -------------------------------------------------------------------------------- 1 | // This would typically be placed in cypress/integration/e2e.test.js 2 | 3 | describe('End-to-End Test: Users App', () => { 4 | it('should visit the app and fetch a user', () => { 5 | cy.visit('http://localhost:3000'); 6 | cy.request('GET', '/users/1').then(response => { 7 | expect(response.status).to.eq(200); 8 | expect(response.body).to.have.property('name', 'User1'); 9 | }); 10 | }); 11 | }); 12 | 13 | // To run this in a Node.js environment: 14 | // 1. Initialize a project: npm init -y 15 | // 2. Install dependencies: npm install express cypress --save-dev 16 | // 3. Save app.js and db.js in the project directory 17 | // 4. Start the app: node -e "require('./app').listen(3000)" 18 | // 5. Initialize Cypress: npx cypress open 19 | // 6. Place this file in cypress/integration/e2e.test.js 20 | // 7. Run the test via the Cypress UI 21 | // Note: This code won't execute here due to network and runtime restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/03 Asynchronous Programming/01 Callbacks/Callbacks.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Callbacks 2 | // Callbacks are functions passed as arguments to handle asynchronous operations. 3 | 4 | // Simulate an asynchronous operation with a callback 5 | function fetchData(callback) { 6 | setTimeout(() => { 7 | const data = 'Data fetched using a callback'; 8 | callback(null, data); // First argument is error (null if no error), second is result 9 | }, 1000); 10 | } 11 | 12 | // Using the callback 13 | console.log('Start'); 14 | fetchData((err, data) => { 15 | if (err) { 16 | console.error('Error:', err); 17 | return; 18 | } 19 | console.log('Callback Result:', data); 20 | }); 21 | console.log('End'); 22 | 23 | // Expected Output: 24 | // Start 25 | // End 26 | // Callback Result: Data fetched using a callback (after 1 second) 27 | 28 | // To run this in a Node.js environment: 29 | // 1. Save this file as Callbacks.js 30 | // 2. Open a terminal and navigate to the file's directory 31 | // 3. Run: node Callbacks.js -------------------------------------------------------------------------------- /Node Js Fundamentals/03 Asynchronous Programming/03 Async Await/AsyncAwait.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Async/Await 2 | // Async/Await makes asynchronous code look synchronous, built on top of Promises. 3 | 4 | // Create a Promise for an asynchronous operation 5 | function fetchData() { 6 | return new Promise((resolve) => { 7 | setTimeout(() => { 8 | const data = 'Data fetched using Async/Await'; 9 | resolve(data); 10 | }, 1000); 11 | }); 12 | } 13 | 14 | // Using async/await 15 | async function processData() { 16 | console.log('Start'); 17 | const data = await fetchData(); 18 | console.log('Async/Await Result:', data); 19 | console.log('End'); 20 | } 21 | 22 | // Execute the async function 23 | processData(); 24 | 25 | // Expected Output: 26 | // Start 27 | // Async/Await Result: Data fetched using Async/Await (after 1 second) 28 | // End 29 | 30 | // To run this in a Node.js environment: 31 | // 1. Save this file as AsyncAwait.js 32 | // 2. Open a terminal and navigate to the file's directory 33 | // 3. Run: node AsyncAwait.js -------------------------------------------------------------------------------- /Node Js Fundamentals/11 Deployment and DevOps/03 Dockerizing Node.js Apps/Dockerfile.txt: -------------------------------------------------------------------------------- 1 | # Main Learning Points: Dockerizing Node.js Apps 2 | # Docker containerizes applications for consistent deployment. 3 | 4 | # Use the official Node.js image 5 | FROM node:18 6 | 7 | # Set working directory 8 | WORKDIR /usr/src/app 9 | 10 | # Copy package.json and install dependencies 11 | COPY package*.json ./ 12 | RUN npm install 13 | 14 | # Copy the rest of the application code 15 | COPY . . 16 | 17 | # Expose the port the app runs on 18 | EXPOSE 3000 19 | 20 | # Command to run the app 21 | CMD ["node", "app.js"] 22 | 23 | # To use this Dockerfile in a Node.js environment: 24 | # 1. Initialize a project: npm init -y 25 | # 2. Install Express: npm install express 26 | # 3. Save app.js in the project directory 27 | # 4. Save this file as Dockerfile 28 | # 5. Build the Docker image: docker build -t my-node-app . 29 | # 6. Run the Docker container: docker run -p 3000:3000 my-node-app 30 | # 7. Visit: http://localhost:3000 31 | # Note: This code won't execute here as Docker requires a runtime environment. -------------------------------------------------------------------------------- /Node Js Fundamentals/11 Deployment and DevOps/01 Environment Variables/envConfig.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Environment Variables 2 | // Environment variables securely manage configuration settings. 3 | 4 | // Note: Requires dotenv (npm install dotenv) 5 | require('dotenv').config(); 6 | const express = require('express'); 7 | const app = express(); 8 | 9 | // Access environment variables 10 | const API_KEY = process.env.API_KEY || 'default-api-key'; 11 | const PORT = process.env.PORT || 3000; 12 | 13 | // Sample route using environment variable 14 | app.get('/', (req, res) => { 15 | res.json({ message: `API Key: ${API_KEY}` }); 16 | }); 17 | 18 | app.listen(PORT, () => { 19 | console.log(`Server running on port ${PORT}`); 20 | }); 21 | 22 | // To run this in a Node.js environment: 23 | // 1. Initialize a project: npm init -y 24 | // 2. Install dependencies: npm install express dotenv 25 | // 3. Create a .env file with: API_KEY=your-api-key 26 | // 4. Save this file as envConfig.js 27 | // 5. Run: node envConfig.js 28 | // 6. Visit: http://localhost:3000 29 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/01 Node.js Basics/05 Node.js CLI and REPL/NodeCLI.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Node.js CLI and REPL 2 | // Node.js CLI allows running JavaScript files; REPL provides an interactive shell for executing code. 3 | 4 | // This file contains instructions for using the Node.js CLI and REPL. 5 | 6 | // 1. Node.js CLI (Command Line Interface) 7 | // To run a JavaScript file using the Node.js CLI: 8 | // - Save a file, e.g., script.js, with some code like: 9 | // console.log('Hello from Node.js CLI!'); 10 | // - Open a terminal and navigate to the file's directory 11 | // - Run: node script.js 12 | // - Output: Hello from Node.js CLI! 13 | 14 | // 2. Node.js REPL (Read-Eval-Print Loop) 15 | // To start the REPL: 16 | // - Open a terminal 17 | // - Run: node 18 | // - You'll enter an interactive shell where you can type JavaScript code 19 | // - Example commands in REPL: 20 | // > 1 + 2 21 | // 3 22 | // > const greet = () => console.log('Hello from REPL!'); 23 | // > greet() 24 | // Hello from REPL! 25 | // - To exit the REPL, type: .exit or press Ctrl+C twice 26 | 27 | // This file is for reference and cannot be executed directly here. -------------------------------------------------------------------------------- /Node Js Fundamentals/07 Databases/05 Database Migrations/example-migration.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = { 4 | up: async (queryInterface, Sequelize) => { 5 | await queryInterface.createTable('users', { 6 | id: { 7 | type: Sequelize.INTEGER, 8 | primaryKey: true, 9 | autoIncrement: true 10 | }, 11 | name: { 12 | type: Sequelize.STRING, 13 | allowNull: false 14 | }, 15 | email: { 16 | type: Sequelize.STRING, 17 | allowNull: false, 18 | unique: true 19 | }, 20 | age: { 21 | type: Sequelize.INTEGER 22 | }, 23 | createdAt: { 24 | type: Sequelize.DATE, 25 | allowNull: false 26 | }, 27 | updatedAt: { 28 | type: Sequelize.DATE, 29 | allowNull: false 30 | } 31 | }); 32 | }, 33 | 34 | down: async (queryInterface, Sequelize) => { 35 | await queryInterface.dropTable('users'); 36 | } 37 | }; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 rohanmistry231 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Node Js Fundamentals/04 File System/01 Reading and Writing Files (fs module)/ReadWriteFiles.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Reading and Writing Files (fs module) 2 | // The fs module provides methods to interact with the file system in Node.js. 3 | 4 | const fs = require('fs'); 5 | 6 | // Writing to a file asynchronously 7 | fs.writeFile('example.txt', 'Hello, Node.js!', (err) => { 8 | if (err) { 9 | console.error('Error writing file:', err); 10 | return; 11 | } 12 | console.log('File written successfully'); 13 | 14 | // Reading from a file asynchronously 15 | fs.readFile('example.txt', 'utf8', (err, data) => { 16 | if (err) { 17 | console.error('Error reading file:', err); 18 | return; 19 | } 20 | console.log('File content:', data); 21 | }); 22 | }); 23 | 24 | // Expected Output (in a real Node.js environment): 25 | // File written successfully 26 | // File content: Hello, Node.js! 27 | 28 | // To run this in a Node.js environment: 29 | // 1. Save this file as ReadWriteFiles.js 30 | // 2. Open a terminal and navigate to the file's directory 31 | // 3. Run: node ReadWriteFiles.js 32 | // Note: This code won't execute here due to file I/O restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/03 Asynchronous Programming/02 Promises/Promises.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Promises 2 | // Promises provide a cleaner way to handle asynchronous operations, avoiding callback hell. 3 | 4 | // Create a Promise for an asynchronous operation 5 | function fetchData() { 6 | return new Promise((resolve, reject) => { 7 | setTimeout(() => { 8 | const data = 'Data fetched using a Promise'; 9 | resolve(data); 10 | }, 1000); 11 | }); 12 | } 13 | 14 | // Using the Promise 15 | console.log('Start'); 16 | fetchData() 17 | .then(data => { 18 | console.log('Promise Result:', data); 19 | return 'Additional data'; 20 | }) 21 | .then(moreData => { 22 | console.log('Chained Result:', moreData); 23 | }) 24 | .catch(err => { 25 | console.error('Error:', err); 26 | }); 27 | console.log('End'); 28 | 29 | // Expected Output: 30 | // Start 31 | // End 32 | // Promise Result: Data fetched using a Promise (after 1 second) 33 | // Chained Result: Additional data 34 | 35 | // To run this in a Node.js environment: 36 | // 1. Save this file as Promises.js 37 | // 2. Open a terminal and navigate to the file's directory 38 | // 3. Run: node Promises.js -------------------------------------------------------------------------------- /Node Js Fundamentals/10 Testing/04 API Testing with Supertest/app.api.test.js: -------------------------------------------------------------------------------- 1 | const request = require('supertest'); 2 | const app = require('./app'); 3 | 4 | describe('API Test: Users API', () => { 5 | test('should create a new user', async () => { 6 | const res = await request(app) 7 | .post('/users') 8 | .send({ name: 'Alice', email: 'alice@example.com' }) 9 | .expect(201); 10 | 11 | expect(res.body).toEqual({ 12 | message: 'User created', 13 | user: { name: 'Alice', email: 'alice@example.com' } 14 | }); 15 | }); 16 | 17 | test('should fetch a user by ID', async () => { 18 | const res = await request(app) 19 | .get('/users/2') 20 | .expect(200); 21 | 22 | expect(res.body).toEqual({ id: 2, name: 'User2' }); 23 | }); 24 | }); 25 | 26 | // To run this in a Node.js environment: 27 | // 1. Initialize a project: npm init -y 28 | // 2. Install dependencies: npm install express supertest jest --save-dev 29 | // 3. Save this file as app.api.test.js 30 | // 4. Save app.js and db.js in the same directory 31 | // 5. Run: npx jest app.api.test.js 32 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/08 Authentication and Security/05 Securing APIs (CORS Helmet)/SecureAPI.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Securing APIs (CORS, Helmet) 2 | // CORS enables cross-origin requests; Helmet adds security headers. 3 | 4 | // Note: Requires Express, CORS, and Helmet (npm install express cors helmet) 5 | const express = require('express'); 6 | const cors = require('cors'); 7 | const helmet = require('helmet'); 8 | const app = express(); 9 | 10 | // Enable CORS for specific origins 11 | app.use(cors({ 12 | origin: 'http://localhost:3000', 13 | methods: ['GET', 'POST'] 14 | })); 15 | 16 | // Use Helmet to set security headers 17 | app.use(helmet()); 18 | 19 | // Sample route 20 | app.get('/api/data', (req, res) => { 21 | res.json({ message: 'Secure API data' }); 22 | }); 23 | 24 | app.listen(3003, () => { 25 | console.log('Server running at http://localhost:3003'); 26 | }); 27 | 28 | // To run this in a Node.js environment: 29 | // 1. Initialize a project: npm init -y 30 | // 2. Install dependencies: npm install express cors helmet 31 | // 3. Save this file as SecureAPI.js 32 | // 4. Run: node SecureAPI.js 33 | // 5. Test: 34 | // - GET http://localhost:3003/api/data (from allowed origin) 35 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/05 HTTP and Networking/04 TCP UDP Servers (net module)/TCPServer.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: TCP/UDP Servers (net module) 2 | // The net module allows creating TCP servers and clients. 3 | 4 | const net = require('net'); 5 | 6 | // Create a TCP server 7 | const server = net.createServer((socket) => { 8 | console.log('Client connected'); 9 | 10 | // Send a message to the client 11 | socket.write('Hello from TCP Server!\n'); 12 | 13 | // Handle data from the client 14 | socket.on('data', (data) => { 15 | console.log('Received from client:', data.toString()); 16 | }); 17 | 18 | // Handle client disconnection 19 | socket.on('end', () => { 20 | console.log('Client disconnected'); 21 | }); 22 | }); 23 | 24 | // Listen on port 3002 25 | server.listen(3002, () => { 26 | console.log('TCP Server running on port 3002'); 27 | }); 28 | 29 | // To run this in a Node.js environment: 30 | // 1. Save this file as TCPServer.js 31 | // 2. Open a terminal and navigate to the file's directory 32 | // 3. Run: node TCPServer.js 33 | // 4. Connect to the server using a TCP client, e.g., telnet: 34 | // - Run: telnet localhost 3002 35 | // - You should see "Hello from TCP Server!" and can send messages 36 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/06 Express.js Framework/04 Template Engines (EJS Pug)/TemplateEngines.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Template Engines (e.g., EJS) 2 | // Template engines allow rendering dynamic HTML content. 3 | 4 | // Note: Requires Express and EJS installation (npm install express ejs) 5 | const express = require('express'); 6 | const app = express(); 7 | 8 | // Set EJS as the template engine 9 | app.set('view engine', 'ejs'); 10 | // In a real setup, you'd set the views directory: app.set('views', './views'); 11 | 12 | app.get('/', (req, res) => { 13 | // Render an EJS template with dynamic data 14 | res.render('example-template', { title: 'EJS Demo', message: 'Hello from EJS!' }); 15 | }); 16 | 17 | // Start the server 18 | const PORT = 3003; 19 | app.listen(PORT, () => { 20 | console.log(`Express server running on http://localhost:${PORT}`); 21 | }); 22 | 23 | // To run this in a Node.js environment: 24 | // 1. Initialize a project: npm init -y 25 | // 2. Install Express and EJS: npm install express ejs 26 | // 3. Create a views directory and save the EJS template as views/example-template.ejs 27 | // 4. Save this file as TemplateEngines.js 28 | // 5. Run: node TemplateEngines.js 29 | // 6. Visit http://localhost:3003 in a browser 30 | // Note: This code won't execute here due to file I/O and network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/11 Deployment and DevOps/04 CI CD Pipelines/github-actions.yaml: -------------------------------------------------------------------------------- 1 | # Main Learning Points: CI/CD Pipelines 2 | # Automate testing and deployment with CI/CD pipelines. 3 | 4 | name: Node.js CI/CD 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v3 18 | 19 | - name: Setup Node.js 20 | uses: actions/setup-node@v3 21 | with: 22 | node-version: '18' 23 | 24 | - name: Install Dependencies 25 | run: npm install 26 | 27 | - name: Run Tests 28 | run: npm test 29 | 30 | - name: Build Docker Image 31 | run: docker build -t my-node-app . 32 | 33 | # To use this in a Node.js environment: 34 | # 1. Initialize a project: npm init -y 35 | # 2. Install Express: npm install express 36 | # 3. Save app.js and Dockerfile in the project directory 37 | # 4. Add a test script in package.json: "test": "echo \"Running tests\" && exit 0" 38 | # 5. Create a .github/workflows directory in your repo 39 | # 6. Save this file as .github/workflows/github-actions.yml 40 | # 7. Push to GitHub; the pipeline will run automatically on push or pull request to main 41 | # Note: This pipeline won't execute here as it requires GitHub Actions. -------------------------------------------------------------------------------- /Node Js Fundamentals/09 Performance Optimization/04 Rate Limiting/RateLimiting.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Rate Limiting 2 | // Rate limiting prevents abuse by restricting the number of requests a client can make. 3 | 4 | // Note: Requires Express and express-rate-limit (npm install express express-rate-limit) 5 | const express = require('express'); 6 | const rateLimit = require('express-rate-limit'); 7 | const app = express(); 8 | 9 | // Configure rate limiter: 5 requests per minute 10 | const limiter = rateLimit({ 11 | windowMs: 60 * 1000, // 1 minute 12 | max: 5, // Limit each IP to 5 requests per windowMs 13 | message: 'Too many requests, please try again later.' 14 | }); 15 | 16 | app.use(limiter); 17 | 18 | // Sample route 19 | app.get('/api', (req, res) => { 20 | res.json({ message: 'Rate-limited API' }); 21 | }); 22 | 23 | app.listen(3003, () => { 24 | console.log('Server running at http://localhost:3003'); 25 | }); 26 | 27 | // To run this in a Node.js environment: 28 | // 1. Initialize a project: npm init -y 29 | // 2. Install dependencies: npm install express express-rate-limit 30 | // 3. Save this file as RateLimiting.js 31 | // 4. Run: node RateLimiting.js 32 | // 5. Test: Make more than 5 requests to http://localhost:3003/api within a minute 33 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/04 File System/03 Streams and Buffers/StreamsAndBuffers.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Streams and Buffers 2 | // Streams allow processing data in chunks; Buffers handle raw binary data. 3 | 4 | const fs = require('fs'); 5 | 6 | // Create a readable stream 7 | const readStream = fs.createReadStream('input.txt', { encoding: 'utf8' }); 8 | 9 | // Create a writable stream 10 | const writeStream = fs.createWriteStream('output.txt'); 11 | 12 | // Pipe the readable stream to the writable stream 13 | readStream.pipe(writeStream); 14 | 15 | // Handle events on the streams 16 | readStream.on('data', (chunk) => { 17 | console.log('Received chunk:', chunk); 18 | }); 19 | 20 | readStream.on('end', () => { 21 | console.log('Finished reading file'); 22 | }); 23 | 24 | writeStream.on('finish', () => { 25 | console.log('Finished writing file'); 26 | }); 27 | 28 | // Using Buffers 29 | const buffer = Buffer.from('Hello, Node.js!'); 30 | console.log('Buffer:', buffer); 31 | console.log('Buffer to string:', buffer.toString()); 32 | 33 | // To use this in a real Node.js environment: 34 | // 1. Create a file named input.txt with some content (e.g., "Hello, Streams!") 35 | // 2. Save this file as StreamsAndBuffers.js 36 | // 3. Open a terminal and navigate to the file's directory 37 | // 4. Run: node StreamsAndBuffers.js 38 | // Note: This code won't execute here due to file I/O restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/09 Performance Optimization/01 Clustering with cluster Module/Clustering.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Clustering with cluster Module 2 | // The cluster module allows Node.js to utilize multiple CPU cores by forking worker processes. 3 | 4 | const cluster = require('cluster'); 5 | const http = require('http'); 6 | const numCPUs = require('os').cpus().length; 7 | 8 | // Check if this is the master process 9 | if (cluster.isMaster) { 10 | console.log(`Master ${process.pid} is running`); 11 | 12 | // Fork workers for each CPU 13 | for (let i = 0; i < numCPUs; i++) { 14 | cluster.fork(); 15 | } 16 | 17 | cluster.on('exit', (worker, code, signal) => { 18 | console.log(`Worker ${worker.process.pid} died`); 19 | }); 20 | } else { 21 | // Workers can share any TCP connection (HTTP server in this case) 22 | http.createServer((req, res) => { 23 | res.writeHead(200); 24 | res.end(`Hello from worker ${process.pid}\n`); 25 | }).listen(3000); 26 | 27 | console.log(`Worker ${process.pid} started`); 28 | } 29 | 30 | // To run this in a Node.js environment: 31 | // 1. Save this file as Clustering.js 32 | // 2. Open a terminal and navigate to the file's directory 33 | // 3. Run: node Clustering.js 34 | // 4. Visit http://localhost:3000 multiple times to see different workers respond 35 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/02 Modules and Packages/03 require vs import/RequireVsImport.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: require vs. import 2 | // require is used in CommonJS; import is used in ES Modules with different syntax and behavior. 3 | 4 | // CommonJS Example (require) 5 | // Export (imagine this as a separate file, e.g., helper.js) 6 | const greet = (name) => `Hello, ${name}!`; 7 | module.exports = { greet }; 8 | 9 | // Import using require 10 | // const helper = require('./helper.js'); 11 | const helper = { greet }; // Simulated for this demo 12 | console.log('CommonJS (require):', helper.greet('Alice')); // Hello, Alice! 13 | 14 | // ES Modules Example (import) 15 | // Export (imagine this as a separate file, e.g., utils.js) 16 | export const farewell = (name) => `Goodbye, ${name}!`; 17 | 18 | // Import using import 19 | // import { farewell } from './utils.js'; 20 | const utils = { farewell }; // Simulated for this demo 21 | console.log('ES Modules (import):', utils.farewell('Bob')); // Goodbye, Bob! 22 | 23 | // Key Differences: 24 | // - require is synchronous; import can be asynchronous (with dynamic import) 25 | // - CommonJS modules are loaded entirely; ES Modules support tree-shaking 26 | // - Use "type": "module" in package.json for ES Modules 27 | 28 | // To run this in a Node.js environment: 29 | // 1. For CommonJS: Use the require example as is 30 | // 2. For ES Modules: Add "type": "module" to package.json 31 | // 3. Run: node RequireVsImport.js -------------------------------------------------------------------------------- /Node Js Fundamentals/11 Deployment and DevOps/05 Cloud Deployment (AWS Heroku Vercel)/README.md: -------------------------------------------------------------------------------- 1 | # Main Learning Points: Cloud Deployment (AWS, Heroku, Vercel) 2 | 3 | ## Deploying to Heroku 4 | 1. Install Heroku CLI: `npm install -g heroku` 5 | 2. Login: `heroku login` 6 | 3. Initialize a project with app.js and package.json 7 | 4. Create a Procfile: 8 | ``` 9 | web: node app.js 10 | ``` 11 | 5. Create a Heroku app: `heroku create my-node-app` 12 | 6. Deploy: `git push heroku main` 13 | 7. Open the app: `heroku open` 14 | 15 | ## Deploying to Vercel 16 | 1. Install Vercel CLI: `npm install -g vercel` 17 | 2. Initialize a project with app.js and package.json 18 | 3. Add a `vercel.json` file: 19 | ```json 20 | { 21 | "version": 2, 22 | "builds": [{ "src": "app.js", "use": "@vercel/node" }], 23 | "routes": [{ "src": "/(.*)", "dest": "app.js" }] 24 | } 25 | ``` 26 | 4. Deploy: `vercel --prod` 27 | 5. Access the deployed app via the provided URL 28 | 29 | ## Deploying to AWS (Elastic Beanstalk) 30 | 1. Install AWS CLI: `pip install awscli` 31 | 2. Configure AWS: `aws configure` 32 | 3. Initialize a project with app.js and package.json 33 | 4. Initialize Elastic Beanstalk: `eb init -p node.js my-node-app --region us-east-1` 34 | 5. Create an environment: `eb create my-node-env` 35 | 6. Deploy: `eb deploy` 36 | 7. Open the app: `eb open` 37 | 38 | # Note: Deployment cannot be executed here as it requires cloud provider access. -------------------------------------------------------------------------------- /Node Js Fundamentals/09 Performance Optimization/06 Profiling and Debugging/ProfilingDebugging.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Profiling and Debugging 2 | // Node.js provides tools for profiling and debugging performance issues. 3 | 4 | // Sample function to profile 5 | function computeSomething() { 6 | let sum = 0; 7 | for (let i = 0; i < 1e7; i++) { 8 | sum += i; 9 | } 10 | return sum; 11 | } 12 | 13 | // Run the function multiple times 14 | console.log('Starting computation...'); 15 | for (let i = 0; i < 5; i++) { 16 | console.log(`Result ${i + 1}:`, computeSomething()); 17 | } 18 | console.log('Computation finished'); 19 | 20 | // To profile this in a Node.js environment: 21 | // 1. Save this file as ProfilingDebugging.js 22 | // 2. Open a terminal and navigate to the file's directory 23 | // 3. Run with profiling: node --prof ProfilingDebugging.js 24 | // 4. This generates a tick file (e.g., isolate-0x...-v8.log) 25 | // 5. Process the tick file: node --prof-process isolate-0x...-v8.log > profile.txt 26 | // 6. Inspect profile.txt for performance insights 27 | 28 | // To debug this in a Node.js environment: 29 | // 1. Run with inspector: node --inspect ProfilingDebugging.js 30 | // 2. Open Chrome and navigate to chrome://inspect 31 | // 3. Click "Open dedicated DevTools for Node" 32 | // 4. Set breakpoints, watch variables, and step through the code 33 | 34 | // Note: This code won't execute profiling/debugging here due to runtime restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/06 Express.js Framework/05 Error Handling/ErrorHandling.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Error Handling 2 | // Express provides middleware for handling errors gracefully. 3 | 4 | // Note: Requires Express installation (npm install express) 5 | const express = require('express'); 6 | const app = express(); 7 | 8 | // Route that throws an error 9 | app.get('/error', (req, res, next) => { 10 | const err = new Error('Something went wrong!'); 11 | err.status = 500; 12 | next(err); 13 | }); 14 | 15 | // Error-handling middleware 16 | app.use((err, req, res, next) => { 17 | res.status(err.status || 500); 18 | res.json({ 19 | error: { 20 | message: err.message, 21 | status: err.status || 500 22 | } 23 | }); 24 | }); 25 | 26 | // Normal route 27 | app.get('/', (req, res) => { 28 | res.send('Home Page'); 29 | }); 30 | 31 | // Start the server 32 | const PORT = 3004; 33 | app.listen(PORT, () => { 34 | console.log(`Express server running on http://localhost:${PORT}`); 35 | }); 36 | 37 | // To run this in a Node.js environment: 38 | // 1. Initialize a project: npm init -y 39 | // 2. Install Express: npm install express 40 | // 3. Save this file as ErrorHandling.js 41 | // 4. Run: node ErrorHandling.js 42 | // 5. Test routes: 43 | // - GET http://localhost:3004/ (Home Page) 44 | // - GET http://localhost:3004/error (Error response) 45 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/06 Express.js Framework/02 Routing and Middleware/RoutingMiddleware.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Routing and Middleware 2 | // Routing defines endpoints; Middleware processes requests before reaching routes. 3 | 4 | // Note: Requires Express installation (npm install express) 5 | const express = require('express'); 6 | const app = express(); 7 | 8 | // Middleware to log requests 9 | app.use((req, res, next) => { 10 | console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`); 11 | next(); 12 | }); 13 | 14 | // Routes 15 | app.get('/', (req, res) => { 16 | res.send('Home Page'); 17 | }); 18 | 19 | app.get('/about', (req, res) => { 20 | res.send('About Page'); 21 | }); 22 | 23 | app.post('/submit', (req, res) => { 24 | res.send('Data submitted'); 25 | }); 26 | 27 | // Start the server 28 | const PORT = 3001; 29 | app.listen(PORT, () => { 30 | console.log(`Express server running on http://localhost:${PORT}`); 31 | }); 32 | 33 | // To run this in a Node.js environment: 34 | // 1. Initialize a project: npm init -y 35 | // 2. Install Express: npm install express 36 | // 3. Save this file as RoutingMiddleware.js 37 | // 4. Run: node RoutingMiddleware.js 38 | // 5. Test routes: 39 | // - GET http://localhost:3001/ 40 | // - GET http://localhost:3001/about 41 | // - POST http://localhost:3001/submit (e.g., using curl: curl -X POST http://localhost:3001/submit) 42 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/07 Databases/05 Database Migrations/SequelizeMigrations.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Database Migrations 2 | // Migrations manage database schema changes over time. 3 | 4 | // Note: Requires Sequelize, Sequelize CLI, and PostgreSQL driver (npm install sequelize sequelize-cli pg pg-hstore) 5 | const { Sequelize } = require('sequelize'); 6 | 7 | const sequelize = new Sequelize('postgres://user:password@localhost:5432/mydatabase', { 8 | dialect: 'postgres' 9 | }); 10 | 11 | // Test the connection 12 | (async () => { 13 | try { 14 | await sequelize.authenticate(); 15 | console.log('Connected to PostgreSQL'); 16 | console.log('Run migrations using Sequelize CLI: npx sequelize db:migrate'); 17 | } catch (err) { 18 | console.error('Error:', err.message); 19 | } 20 | })(); 21 | 22 | // To set up migrations in a Node.js environment: 23 | // 1. Ensure PostgreSQL is running locally 24 | // 2. Initialize a project: npm init -y 25 | // 3. Install Sequelize, Sequelize CLI, and PostgreSQL driver: npm install sequelize sequelize-cli pg pg-hstore 26 | // 4. Initialize Sequelize CLI: npx sequelize init 27 | // 5. Configure config/config.json with your database credentials 28 | // 6. Create a migration: npx sequelize migration:generate --name create-users-table 29 | // 7. Edit the migration file (see example-migration.js) 30 | // 8. Run migrations: npx sequelize db:migrate 31 | // Note: This code won't execute here due to database restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/09 Performance Optimization/02 Load Balancing/LoadBalancing.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Load Balancing 2 | // Clustering can be used for load balancing by distributing requests across workers. 3 | 4 | const cluster = require('cluster'); 5 | const http = require('http'); 6 | const numCPUs = require('os').cpus().length; 7 | 8 | if (cluster.isMaster) { 9 | console.log(`Master ${process.pid} is running`); 10 | 11 | // Fork workers 12 | for (let i = 0; i < numCPUs; i++) { 13 | cluster.fork(); 14 | } 15 | 16 | cluster.on('exit', (worker, code, signal) => { 17 | console.log(`Worker ${worker.process.pid} died`); 18 | cluster.fork(); // Restart a worker if it dies 19 | }); 20 | } else { 21 | // Each worker runs an HTTP server 22 | http.createServer((req, res) => { 23 | res.writeHead(200); 24 | res.end(`Handled by worker ${process.pid}\n`); 25 | }).listen(3001); 26 | 27 | console.log(`Worker ${process.pid} started`); 28 | } 29 | 30 | // Note: Node.js automatically balances HTTP requests across workers (round-robin by default on most platforms). 31 | 32 | // To run this in a Node.js environment: 33 | // 1. Save this file as LoadBalancing.js 34 | // 2. Open a terminal and navigate to the file's directory 35 | // 3. Run: node LoadBalancing.js 36 | // 4. Visit http://localhost:3001 multiple times to see requests distributed across workers 37 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/11 Deployment and DevOps/02 PM2 for Process Management/pm2Config.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: PM2 for Process Management 2 | // PM2 is a process manager for Node.js applications. 3 | 4 | // Use the app.js file as the main application 5 | const app = require('./app'); 6 | 7 | // PM2 is typically configured via CLI or an ecosystem file, but this comment block explains the setup. 8 | 9 | // To use PM2 with app.js in a Node.js environment: 10 | // 1. Initialize a project: npm init -y 11 | // 2. Install dependencies: npm install express 12 | // 3. Install PM2 globally: npm install pm2 -g 13 | // 4. Save app.js in the project directory 14 | // 5. Start the app with PM2: pm2 start app.js --name "my-app" 15 | // 6. Monitor the app: pm2 monit 16 | // 7. View logs: pm2 logs 17 | // 8. Restart on file change: pm2 start app.js --name "my-app" --watch 18 | // 9. Stop the app: pm2 stop my-app 19 | // 10. Delete the app: pm2 delete my-app 20 | 21 | // Optional: Create an ecosystem.config.js for advanced configuration 22 | // ecosystem.config.js example: 23 | /* 24 | module.exports = { 25 | apps: [{ 26 | name: 'my-app', 27 | script: './app.js', 28 | instances: 'max', 29 | exec_mode: 'cluster', 30 | env: { 31 | NODE_ENV: 'production', 32 | PORT: 3000 33 | } 34 | }] 35 | }; 36 | */ 37 | 38 | // Then run: pm2 start ecosystem.config.js 39 | 40 | // Note: This code won't execute here as PM2 requires a Node.js runtime environment. -------------------------------------------------------------------------------- /Node Js Fundamentals/07 Databases/01 MongoDB with Mongoose/MongoDBWithMongoose.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: MongoDB with Mongoose 2 | // Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js. 3 | 4 | // Note: Requires Mongoose installation (npm install mongoose) 5 | const mongoose = require('mongoose'); 6 | 7 | // Connect to MongoDB 8 | mongoose.connect('mongodb://localhost:27017/mydatabase', { 9 | useNewUrlParser: true, 10 | useUnifiedTopology: true 11 | }) 12 | .then(() => console.log('Connected to MongoDB')) 13 | .catch(err => console.error('MongoDB connection error:', err)); 14 | 15 | // Define a schema 16 | const userSchema = new mongoose.Schema({ 17 | name: String, 18 | email: String, 19 | age: Number 20 | }); 21 | 22 | // Create a model 23 | const User = mongoose.model('User', userSchema); 24 | 25 | // Example usage: Create a new user 26 | const newUser = new User({ 27 | name: 'Alice', 28 | email: 'alice@example.com', 29 | age: 25 30 | }); 31 | 32 | newUser.save() 33 | .then(user => console.log('User saved:', user)) 34 | .catch(err => console.error('Error saving user:', err)); 35 | 36 | // To run this in a Node.js environment: 37 | // 1. Ensure MongoDB is running locally (mongod) 38 | // 2. Initialize a project: npm init -y 39 | // 3. Install Mongoose: npm install mongoose 40 | // 4. Save this file as MongoDBWithMongoose.js 41 | // 5. Run: node MongoDBWithMongoose.js 42 | // Note: This code won't execute here due to database restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/05 HTTP and Networking/05 WebSockets with ws/WebSocketServer.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: WebSockets with ws 2 | // The ws library enables WebSocket communication in Node.js. 3 | 4 | // Note: Requires the ws package (npm install ws) 5 | const WebSocket = require('ws'); 6 | 7 | // Create a WebSocket server 8 | const wss = new WebSocket.Server({ port: 3003 }); 9 | 10 | wss.on('connection', (ws) => { 11 | console.log('Client connected to WebSocket'); 12 | 13 | // Send a message to the client 14 | ws.send('Hello from WebSocket Server!'); 15 | 16 | // Handle messages from the client 17 | ws.on('message', (message) => { 18 | console.log('Received:', message.toString()); 19 | ws.send(`Server received: ${message}`); 20 | }); 21 | 22 | // Handle client disconnection 23 | ws.on('close', () => { 24 | console.log('Client disconnected from WebSocket'); 25 | }); 26 | }); 27 | 28 | console.log('WebSocket Server running on ws://localhost:3003'); 29 | 30 | // To run this in a Node.js environment: 31 | // 1. Install the ws package: npm install ws 32 | // 2. Save this file as WebSocketServer.js 33 | // 3. Open a terminal and navigate to the file's directory 34 | // 4. Run: node WebSocketServer.js 35 | // 5. Connect using a WebSocket client, e.g., a browser script: 36 | // const ws = new WebSocket('ws://localhost:3003'); 37 | // ws.onmessage = (event) => console.log(event.data); 38 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/02 Modules and Packages/04 Creating and Publishing NPM Packages/README.md: -------------------------------------------------------------------------------- 1 | # MyPackage 2 | 3 | A simple NPM package that capitalizes strings. 4 | 5 | ## Installation 6 | ```bash 7 | npm install my-package 8 | ``` 9 | 10 | ## Usage 11 | ```javascript 12 | const { capitalize } = require('my-package'); 13 | console.log(capitalize('hello')); // Output: Hello 14 | ``` 15 | 16 | ## Publishing Instructions 17 | To create and publish this package to NPM, follow these steps: 18 | 19 | 1. **Initialize the Package** 20 | - Create a new directory for the package: `mkdir my-package` 21 | - Navigate to the directory: `cd my-package` 22 | - Initialize a new NPM package: `npm init -y` 23 | - Update the `package.json` to include: 24 | ```json 25 | { 26 | "name": "my-package", 27 | "version": "1.0.0", 28 | "main": "MyPackage.js", 29 | "author": "Your Name", 30 | "license": "MIT" 31 | } 32 | ``` 33 | 34 | 2. **Add the Code** 35 | - Save the `MyPackage.js` code in this directory as `MyPackage.js` 36 | 37 | 3. **Publish to NPM** 38 | - Log in to NPM: `npm login` 39 | - Publish the package: `npm publish --access public` 40 | - Note: Ensure the package name is unique, or use a scoped name (e.g., `@yourusername/my-package`) 41 | 42 | 4. **Install and Use** 43 | - Install the package in another project: `npm install my-package` 44 | - Use it as shown in the Usage section above 45 | 46 | This README provides a basic setup for publishing an NPM package. -------------------------------------------------------------------------------- /Node Js Fundamentals/04 File System/05 Directory Management/DirectoryManagement.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Directory Management 2 | // The fs module provides methods to create, read, and delete directories. 3 | 4 | const fs = require('fs'); 5 | 6 | // Create a directory 7 | fs.mkdir('my-directory', { recursive: true }, (err) => { 8 | if (err) { 9 | console.error('Error creating directory:', err.message); 10 | return; 11 | } 12 | console.log('Directory created successfully'); 13 | 14 | // Read the contents of a directory 15 | fs.readdir('my-directory', (err, files) => { 16 | if (err) { 17 | console.error('Error reading directory:', err.message); 18 | return; 19 | } 20 | console.log('Directory contents:', files); 21 | 22 | // Remove the directory 23 | fs.rmdir('my-directory', (err) => { 24 | if (err) { 25 | console.error('Error removing directory:', err.message); 26 | return; 27 | } 28 | console.log('Directory removed successfully'); 29 | }); 30 | }); 31 | }); 32 | 33 | // Expected Output (in a real Node.js environment): 34 | // Directory created successfully 35 | // Directory contents: [] 36 | // Directory removed successfully 37 | 38 | // To run this in a Node.js environment: 39 | // 1. Save this file as DirectoryManagement.js 40 | // 2. Open a terminal and navigate to the file's directory 41 | // 3. Run: node DirectoryManagement.js 42 | // Note: This code won't execute here due to file I/O restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/08 Authentication and Security/02 Password Hashing with bcrypt/PasswordHashing.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Password Hashing with bcrypt 2 | // bcrypt securely hashes passwords to store them safely. 3 | 4 | // Note: Requires bcrypt (npm install bcrypt) 5 | const bcrypt = require('bcrypt'); 6 | 7 | // Number of salt rounds for hashing 8 | const saltRounds = 10; 9 | 10 | // Hash a password 11 | const password = 'mySecurePassword'; 12 | 13 | bcrypt.hash(password, saltRounds, (err, hash) => { 14 | if (err) { 15 | console.error('Error hashing password:', err); 16 | return; 17 | } 18 | console.log('Hashed Password:', hash); 19 | 20 | // Verify the password 21 | bcrypt.compare(password, hash, (err, result) => { 22 | if (err) { 23 | console.error('Error verifying password:', err); 24 | return; 25 | } 26 | console.log('Password Match:', result); // true 27 | }); 28 | 29 | // Verify an incorrect password 30 | bcrypt.compare('wrongPassword', hash, (err, result) => { 31 | if (err) { 32 | console.error('Error verifying password:', err); 33 | return; 34 | } 35 | console.log('Incorrect Password Match:', result); // false 36 | }); 37 | }); 38 | 39 | // To run this in a Node.js environment: 40 | // 1. Initialize a project: npm init -y 41 | // 2. Install bcrypt: npm install bcrypt 42 | // 3. Save this file as PasswordHashing.js 43 | // 4. Run: node PasswordHashing.js 44 | // Note: This code won't execute here due to runtime restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/09 Performance Optimization/05 Optimizing Event Loop/OptimizeEventLoop.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Optimizing Event Loop 2 | // Avoid blocking the event loop to keep Node.js responsive. 3 | 4 | // Blocking (synchronous) operation - Bad practice 5 | const blockingOperation = () => { 6 | const start = Date.now(); 7 | while (Date.now() - start < 5000) { 8 | // Simulate CPU-intensive task for 5 seconds 9 | } 10 | return 'Done blocking'; 11 | }; 12 | 13 | // Non-blocking (asynchronous) operation - Good practice 14 | const nonBlockingOperation = () => { 15 | return new Promise(resolve => { 16 | setTimeout(() => resolve('Done non-blocking'), 5000); 17 | }); 18 | }; 19 | 20 | // Example usage 21 | console.log('Start'); 22 | 23 | // Blocking: This will freeze the event loop 24 | console.log(blockingOperation()); 25 | console.log('After blocking'); 26 | 27 | // Non-blocking: Event loop remains responsive 28 | nonBlockingOperation().then(result => { 29 | console.log(result); 30 | console.log('After non-blocking'); 31 | }); 32 | 33 | console.log('End'); 34 | 35 | // Expected Output (in a real Node.js environment): 36 | // Start 37 | // Done blocking (after 5 seconds) 38 | // After blocking 39 | // End 40 | // Done non-blocking (after 5 seconds) 41 | // After non-blocking 42 | 43 | // To run this in a Node.js environment: 44 | // 1. Save this file as OptimizeEventLoop.js 45 | // 2. Open a terminal and navigate to the file's directory 46 | // 3. Run: node OptimizeEventLoop.js 47 | // Note: This code will run here but is meant to demonstrate event loop optimization. -------------------------------------------------------------------------------- /Node Js Fundamentals/07 Databases/03 Connection Pooling/ConnectionPooling.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Connection Pooling 2 | // Connection pooling manages multiple database connections efficiently. 3 | 4 | // Note: Requires Sequelize and PostgreSQL driver (npm install sequelize pg pg-hstore) 5 | const { Sequelize } = require('sequelize'); 6 | 7 | // Initialize Sequelize with connection pooling 8 | const sequelize = new Sequelize('postgres://user:password@localhost:5432/mydatabase', { 9 | dialect: 'postgres', 10 | pool: { 11 | max: 5, // Maximum number of connections in pool 12 | min: 0, // Minimum number of connections in pool 13 | acquire: 30000, // Maximum time (ms) to acquire a connection 14 | idle: 10000 // Maximum time (ms) a connection can be idle before being released 15 | } 16 | }); 17 | 18 | // Test the connection 19 | (async () => { 20 | try { 21 | await sequelize.authenticate(); 22 | console.log('Connected to PostgreSQL with connection pooling'); 23 | console.log('Pool configuration:', sequelize.config.pool); 24 | } catch (err) { 25 | console.error('Error:', err.message); 26 | } 27 | })(); 28 | 29 | // To run this in a Node.js environment: 30 | // 1. Ensure PostgreSQL is running locally 31 | // 2. Initialize a project: npm init -y 32 | // 3. Install Sequelize and PostgreSQL driver: npm install sequelize pg pg-hstore 33 | // 4. Update the connection string with your PostgreSQL credentials 34 | // 5. Save this file as ConnectionPooling.js 35 | // 6. Run: node ConnectionPooling.js 36 | // Note: This code won't execute here due to database restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/06 Express.js Framework/03 Request and Response Objects/RequestResponseObjects.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Request and Response Objects 2 | // req and res objects provide access to request data and response methods. 3 | 4 | // Note: Requires Express installation (npm install express) 5 | const express = require('express'); 6 | const app = express(); 7 | 8 | // Middleware to parse JSON bodies 9 | app.use(express.json()); 10 | 11 | // Route to demonstrate req and res 12 | app.get('/user/:id', (req, res) => { 13 | const userId = req.params.id; // Access URL parameters 14 | const query = req.query; // Access query parameters 15 | res.status(200).json({ 16 | message: 'User fetched', 17 | userId, 18 | query 19 | }); 20 | }); 21 | 22 | app.post('/user', (req, res) => { 23 | const data = req.body; // Access request body 24 | res.status(201).json({ 25 | message: 'User created', 26 | data 27 | }); 28 | }); 29 | 30 | // Start the server 31 | const PORT = 3002; 32 | app.listen(PORT, () => { 33 | console.log(`Express server running on http://localhost:${PORT}`); 34 | }); 35 | 36 | // To run this in a Node.js environment: 37 | // 1. Initialize a project: npm init -y 38 | // 2. Install Express: npm install express 39 | // 3. Save this file as RequestResponseObjects.js 40 | // 4. Run: node RequestResponseObjects.js 41 | // 5. Test routes: 42 | // - GET http://localhost:3002/user/123?name=John 43 | // - POST http://localhost:3002/user (e.g., using curl: curl -X POST -H "Content-Type: application/json" -d '{"name":"John"}' http://localhost:3002/user) 44 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/07 Databases/02 SQL Databases with Sequelize Knex/SequelizeSetup.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: SQL Databases with Sequelize 2 | // Sequelize is an ORM for SQL databases like PostgreSQL, MySQL, etc. 3 | 4 | // Note: Requires Sequelize and PostgreSQL driver (npm install sequelize pg pg-hstore) 5 | const { Sequelize, DataTypes } = require('sequelize'); 6 | 7 | // Initialize Sequelize with PostgreSQL 8 | const sequelize = new Sequelize('postgres://user:password@localhost:5432/mydatabase', { 9 | dialect: 'postgres' 10 | }); 11 | 12 | // Define a model 13 | const User = sequelize.define('User', { 14 | name: { 15 | type: DataTypes.STRING, 16 | allowNull: false 17 | }, 18 | email: { 19 | type: DataTypes.STRING, 20 | allowNull: false, 21 | unique: true 22 | }, 23 | age: { 24 | type: DataTypes.INTEGER 25 | } 26 | }, { 27 | tableName: 'users' 28 | }); 29 | 30 | // Sync the model with the database 31 | (async () => { 32 | try { 33 | await sequelize.authenticate(); 34 | console.log('Connected to PostgreSQL'); 35 | await sequelize.sync({ force: true }); 36 | console.log('User table created'); 37 | } catch (err) { 38 | console.error('Error:', err.message); 39 | } 40 | })(); 41 | 42 | // To run this in a Node.js environment: 43 | // 1. Ensure PostgreSQL is running locally 44 | // 2. Initialize a project: npm init -y 45 | // 3. Install Sequelize and PostgreSQL driver: npm install sequelize pg pg-hstore 46 | // 4. Update the connection string with your PostgreSQL credentials 47 | // 5. Save this file as SequelizeSetup.js 48 | // 6. Run: node SequelizeSetup.js 49 | // Note: This code won't execute here due to database restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/08 Authentication and Security/06 Input Validation and Sanitization/InputValidation.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Input Validation and Sanitization 2 | // Validate and sanitize user input to prevent security issues. 3 | 4 | // Note: Requires Express and express-validator (npm install express express-validator) 5 | const express = require('express'); 6 | const { body, validationResult } = require('express-validator'); 7 | const app = express(); 8 | 9 | app.use(express.json()); 10 | 11 | // Route with validation and sanitization 12 | app.post('/register', 13 | // Validation rules 14 | body('email').isEmail().normalizeEmail(), 15 | body('password').isLength({ min: 6 }).trim().escape(), 16 | body('username').notEmpty().trim().escape(), 17 | (req, res) => { 18 | // Check for validation errors 19 | const errors = validationResult(req); 20 | if (!errors.isEmpty()) { 21 | return res.status(400).json({ errors: errors.array() }); 22 | } 23 | 24 | // Proceed with sanitized data 25 | res.json({ 26 | message: 'User registered', 27 | data: req.body 28 | }); 29 | } 30 | ); 31 | 32 | app.listen(3004, () => { 33 | console.log('Server running at http://localhost:3004'); 34 | }); 35 | 36 | // To run this in a Node.js environment: 37 | // 1. Initialize a project: npm init -y 38 | // 2. Install dependencies: npm install express express-validator 39 | // 3. Save this file as InputValidation.js 40 | // 4. Run: node InputValidation.js 41 | // 5. Test: 42 | // - POST http://localhost:3004/register with body: {"email": "test@example.com", "password": "123456", "username": "test"} 43 | // - Try invalid data to see validation errors 44 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/08 Authentication and Security/01 JWT and OAuth/JWTAuth.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: JWT and OAuth 2 | // JWT (JSON Web Token) is used for stateless authentication; OAuth is for delegated authorization. 3 | 4 | // Note: Requires Express and jsonwebtoken (npm install express jsonwebtoken) 5 | const express = require('express'); 6 | const jwt = require('jsonwebtoken'); 7 | const app = express(); 8 | 9 | app.use(express.json()); 10 | 11 | // Secret key for JWT signing 12 | const JWT_SECRET = 'your_jwt_secret'; 13 | 14 | // Login route to generate a JWT 15 | app.post('/login', (req, res) => { 16 | const user = { id: 1, username: 'testuser' }; // Mock user 17 | const token = jwt.sign(user, JWT_SECRET, { expiresIn: '1h' }); 18 | res.json({ token }); 19 | }); 20 | 21 | // Protected route requiring JWT 22 | app.get('/protected', (req, res) => { 23 | const token = req.headers.authorization?.split(' ')[1]; 24 | if (!token) return res.status(401).json({ message: 'No token provided' }); 25 | 26 | try { 27 | const decoded = jwt.verify(token, JWT_SECRET); 28 | res.json({ message: 'Protected data', user: decoded }); 29 | } catch (err) { 30 | res.status(401).json({ message: 'Invalid token' }); 31 | } 32 | }); 33 | 34 | app.listen(3000, () => { 35 | console.log('Server running at http://localhost:3000'); 36 | }); 37 | 38 | // To run this in a Node.js environment: 39 | // 1. Initialize a project: npm init -y 40 | // 2. Install dependencies: npm install express jsonwebtoken 41 | // 3. Save this file as JWTAuth.js 42 | // 4. Run: node JWTAuth.js 43 | // 5. Test: 44 | // - POST http://localhost:3000/login to get a token 45 | // - GET http://localhost:3000/protected with Authorization header: Bearer 46 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/04 File System/02 Synchronous vs Asynchronous Methods/SyncVsAsync.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Synchronous vs. Asynchronous Methods 2 | // Synchronous methods block the event loop; asynchronous methods do not. 3 | 4 | const fs = require('fs'); 5 | 6 | // Synchronous file writing and reading 7 | console.log('Start Sync'); 8 | try { 9 | fs.writeFileSync('sync-example.txt', 'Hello, Synchronous!'); 10 | console.log('File written synchronously'); 11 | const data = fs.readFileSync('sync-example.txt', 'utf8'); 12 | console.log('File content (sync):', data); 13 | } catch (err) { 14 | console.error('Sync Error:', err.message); 15 | } 16 | console.log('End Sync'); 17 | 18 | // Asynchronous file writing and reading 19 | console.log('Start Async'); 20 | fs.writeFile('async-example.txt', 'Hello, Asynchronous!', (err) => { 21 | if (err) { 22 | console.error('Async Error:', err.message); 23 | return; 24 | } 25 | console.log('File written asynchronously'); 26 | fs.readFile('async-example.txt', 'utf8', (err, data) => { 27 | if (err) { 28 | console.error('Async Error:', err.message); 29 | return; 30 | } 31 | console.log('File content (async):', data); 32 | }); 33 | }); 34 | console.log('End Async'); 35 | 36 | // Expected Output (in a real Node.js environment): 37 | // Start Sync 38 | // File written synchronously 39 | // File content (sync): Hello, Synchronous! 40 | // End Sync 41 | // Start Async 42 | // End Async 43 | // File written asynchronously 44 | // File content (async): Hello, Asynchronous! 45 | 46 | // To run this in a Node.js environment: 47 | // 1. Save this file as SyncVsAsync.js 48 | // 2. Open a terminal and navigate to the file's directory 49 | // 3. Run: node SyncVsAsync.js 50 | // Note: This code won't execute here due to file I/O restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/05 HTTP and Networking/02 Handling Requests and Responses/RequestResponse.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Handling Requests and Responses 2 | // You can handle different HTTP methods and routes with the http module. 3 | 4 | const http = require('http'); 5 | 6 | const server = http.createServer((req, res) => { 7 | // Handle different routes 8 | if (req.url === '/' && req.method === 'GET') { 9 | res.writeHead(200, { 'Content-Type': 'text/plain' }); 10 | res.end('Welcome to the Home Page!\n'); 11 | } else if (req.url === '/about' && req.method === 'GET') { 12 | res.writeHead(200, { 'Content-Type': 'text/plain' }); 13 | res.end('This is the About Page!\n'); 14 | } else if (req.url === '/data' && req.method === 'POST') { 15 | let body = ''; 16 | req.on('data', chunk => { 17 | body += chunk.toString(); 18 | }); 19 | req.on('end', () => { 20 | res.writeHead(200, { 'Content-Type': 'application/json' }); 21 | res.end(JSON.stringify({ message: 'Data received', body })); 22 | }); 23 | } else { 24 | res.writeHead(404, { 'Content-Type': 'text/plain' }); 25 | res.end('Not Found\n'); 26 | } 27 | }); 28 | 29 | server.listen(3001, () => { 30 | console.log('Server running at http://localhost:3001/'); 31 | }); 32 | 33 | // To run this in a Node.js environment: 34 | // 1. Save this file as RequestResponse.js 35 | // 2. Open a terminal and navigate to the file's directory 36 | // 3. Run: node RequestResponse.js 37 | // 4. Test routes: 38 | // - GET http://localhost:3001/ (Home Page) 39 | // - GET http://localhost:3001/about (About Page) 40 | // - POST http://localhost:3001/data (e.g., using curl: curl -X POST -d "test=data" http://localhost:3001/data) 41 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/08 Authentication and Security/03 Session Management/SessionManagement.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Session Management 2 | // express-session manages user sessions with cookies. 3 | 4 | // Note: Requires Express and express-session (npm install express express-session) 5 | const express = require('express'); 6 | const session = require('express-session'); 7 | const app = express(); 8 | 9 | // Configure session middleware 10 | app.use(session({ 11 | secret: 'your_session_secret', 12 | resave: false, 13 | saveUninitialized: false, 14 | cookie: { maxAge: 1000 * 60 * 60 } // 1 hour 15 | })); 16 | 17 | // Route to set session data 18 | app.get('/set-session', (req, res) => { 19 | req.session.user = { id: 1, username: 'testuser' }; 20 | res.send('Session set'); 21 | }); 22 | 23 | // Route to get session data 24 | app.get('/get-session', (req, res) => { 25 | if (req.session.user) { 26 | res.json(req.session.user); 27 | } else { 28 | res.status(401).send('No session found'); 29 | } 30 | }); 31 | 32 | // Route to destroy session (logout) 33 | app.get('/logout', (req, res) => { 34 | req.session.destroy(err => { 35 | if (err) { 36 | return res.status(500).send('Error logging out'); 37 | } 38 | res.send('Logged out'); 39 | }); 40 | }); 41 | 42 | app.listen(3001, () => { 43 | console.log('Server running at http://localhost:3001'); 44 | }); 45 | 46 | // To run this in a Node.js environment: 47 | // 1. Initialize a project: npm init -y 48 | // 2. Install dependencies: npm install express express-session 49 | // 3. Save this file as SessionManagement.js 50 | // 4. Run: node SessionManagement.js 51 | // 5. Test: 52 | // - GET http://localhost:3001/set-session 53 | // - GET http://localhost:3001/get-session 54 | // - GET http://localhost:3001/logout 55 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/07 Databases/06 NoSQL vs SQL Trade-offs/README.md: -------------------------------------------------------------------------------- 1 | # NoSQL vs. SQL Trade-offs 2 | 3 | ## Main Learning Points: NoSQL vs. SQL Trade-offs 4 | Understanding the differences between NoSQL and SQL databases helps in choosing the right database for your application. 5 | 6 | ### SQL Databases (e.g., PostgreSQL, MySQL) 7 | - **Structure**: Relational, uses tables with predefined schemas. 8 | - **Query Language**: SQL (Structured Query Language). 9 | - **Scalability**: Vertical scaling (adding more power to a single server). 10 | - **Consistency**: Strong consistency (ACID transactions). 11 | - **Use Cases**: Applications requiring complex joins, transactions, and structured data (e.g., banking systems, ERP). 12 | - **Challenges**: Less flexible for schema changes, harder to scale horizontally. 13 | 14 | ### NoSQL Databases (e.g., MongoDB) 15 | - **Structure**: Non-relational, uses collections/documents, key-value, graphs, etc. 16 | - **Query Language**: Varies (e.g., MongoDB uses JavaScript-like queries). 17 | - **Scalability**: Horizontal scaling (adding more servers). 18 | - **Consistency**: Eventual consistency (BASE model), though some support stronger consistency. 19 | - **Use Cases**: Applications needing flexibility, scalability, and unstructured data (e.g., social media, IoT). 20 | - **Challenges**: Weaker consistency, complex queries can be harder to optimize. 21 | 22 | ### Trade-offs 23 | - **Schema Flexibility**: NoSQL is more flexible (schema-less), SQL requires predefined schemas. 24 | - **Performance**: NoSQL often performs better for large-scale, distributed systems; SQL excels in structured queries. 25 | - **Complexity**: SQL handles complex relationships well; NoSQL may require denormalization. 26 | - **Learning Curve**: SQL has a standardized query language; NoSQL varies by database type. 27 | 28 | Choose based on your application's needs: SQL for structured data and transactions, NoSQL for scalability and flexibility. -------------------------------------------------------------------------------- /Node Js Fundamentals/08 Authentication and Security/04 Middleware for Authentication/AuthMiddleware.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Middleware for Authentication 2 | // Middleware can protect routes by verifying authentication. 3 | 4 | // Note: Requires Express and jsonwebtoken (npm install express jsonwebtoken) 5 | const express = require('express'); 6 | const jwt = require('jsonwebtoken'); 7 | const app = express(); 8 | 9 | app.use(express.json()); 10 | 11 | const JWT_SECRET = 'your_jwt_secret'; 12 | 13 | // Authentication middleware 14 | const authMiddleware = (req, res, next) => { 15 | const token = req.headers.authorization?.split(' ')[1]; 16 | if (!token) return res.status(401).json({ message: 'No token provided' }); 17 | 18 | try { 19 | const decoded = jwt.verify(token, JWT_SECRET); 20 | req.user = decoded; 21 | next(); 22 | } catch (err) { 23 | res.status(401).json({ message: 'Invalid token' }); 24 | } 25 | }; 26 | 27 | // Login route to generate a token 28 | app.post('/login', (req, res) => { 29 | const user = { id: 1, username: 'testuser' }; 30 | const token = jwt.sign(user, JWT_SECRET, { expiresIn: '1h' }); 31 | res.json({ token }); 32 | }); 33 | 34 | // Protected route using middleware 35 | app.get('/dashboard', authMiddleware, (req, res) => { 36 | res.json({ message: 'Welcome to the dashboard', user: req.user }); 37 | }); 38 | 39 | app.listen(3002, () => { 40 | console.log('Server running at http://localhost:3002'); 41 | }); 42 | 43 | // To run this in a Node.js environment: 44 | // 1. Initialize a project: npm init -y 45 | // 2. Install dependencies: npm install express jsonwebtoken 46 | // 3. Save this file as AuthMiddleware.js 47 | // 4. Run: node AuthMiddleware.js 48 | // 5. Test: 49 | // - POST http://localhost:3002/login to get a token 50 | // - GET http://localhost:3002/dashboard with Authorization header: Bearer 51 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/09 Performance Optimization/03 Caching with Redis/RedisCaching.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Caching with Redis 2 | // Redis is an in-memory data store used for caching to improve performance. 3 | 4 | // Note: Requires Redis server and redis package (npm install redis) 5 | const express = require('express'); 6 | const redis = require('redis'); 7 | const app = express(); 8 | 9 | // Create Redis client 10 | const client = redis.createClient({ 11 | url: 'redis://localhost:6379' 12 | }); 13 | 14 | client.on('error', (err) => console.log('Redis Client Error', err)); 15 | 16 | // Connect to Redis 17 | (async () => { 18 | await client.connect(); 19 | })(); 20 | 21 | // Mock function to simulate a slow database query 22 | const getDataFromDB = (key) => { 23 | return new Promise(resolve => { 24 | setTimeout(() => resolve(`Data for ${key}`), 2000); 25 | }); 26 | }; 27 | 28 | // Route with caching 29 | app.get('/data/:key', async (req, res) => { 30 | const key = req.params.key; 31 | 32 | // Check Redis cache 33 | const cachedData = await client.get(key); 34 | if (cachedData) { 35 | console.log('Cache hit'); 36 | return res.json({ source: 'cache', data: cachedData }); 37 | } 38 | 39 | // Cache miss: fetch from "database" 40 | console.log('Cache miss'); 41 | const data = await getDataFromDB(key); 42 | await client.setEx(key, 60, data); // Cache for 60 seconds 43 | res.json({ source: 'database', data }); 44 | }); 45 | 46 | app.listen(3002, () => { 47 | console.log('Server running at http://localhost:3002'); 48 | }); 49 | 50 | // To run this in a Node.js environment: 51 | // 1. Ensure Redis is running locally (redis-server) 52 | // 2. Initialize a project: npm init -y 53 | // 3. Install dependencies: npm install express redis 54 | // 4. Save this file as RedisCaching.js 55 | // 5. Run: node RedisCaching.js 56 | // 6. Test: GET http://localhost:3002/data/test (first request slow, subsequent requests fast) 57 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/11 Deployment and DevOps/06 Logging and Monitoring/loggingMonitoring.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Logging and Monitoring 2 | // Logging tracks application events; monitoring tracks performance. 3 | 4 | // Note: Requires winston and express-status-monitor (npm install winston express-status-monitor) 5 | const express = require('express'); 6 | const winston = require('winston'); 7 | const statusMonitor = require('express-status-monitor'); 8 | const app = express(); 9 | 10 | // Configure Winston logger 11 | const logger = winston.createLogger({ 12 | level: 'info', 13 | format: winston.format.combine( 14 | winston.format.timestamp(), 15 | winston.format.json() 16 | ), 17 | transports: [ 18 | new winston.transports.File({ filename: 'error.log', level: 'error' }), 19 | new winston.transports.File({ filename: 'combined.log' }), 20 | new winston.transports.Console() 21 | ] 22 | }); 23 | 24 | // Use express-status-monitor for monitoring 25 | app.use(statusMonitor()); 26 | 27 | // Sample route with logging 28 | app.get('/', (req, res) => { 29 | logger.info('Home route accessed', { ip: req.ip }); 30 | res.json({ message: 'Hello from Node.js app!' }); 31 | }); 32 | 33 | // Error handling with logging 34 | app.get('/error', (req, res) => { 35 | logger.error('Error route accessed', { ip: req.ip }); 36 | res.status(500).json({ error: 'Something went wrong' }); 37 | }); 38 | 39 | app.listen(3000, () => { 40 | logger.info('Server started on port 3000'); 41 | }); 42 | 43 | // To run this in a Node.js environment: 44 | // 1. Initialize a project: npm init -y 45 | // 2. Install dependencies: npm install express winston express-status-monitor 46 | // 3. Save this file as loggingMonitoring.js 47 | // 4. Run: node loggingMonitoring.js 48 | // 5. Visit: http://localhost:3000 to see the app 49 | // 6. Visit: http://localhost:3000/status to see the monitoring dashboard 50 | // 7. Check error.log and combined.log for logs 51 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/03 Asynchronous Programming/05 Handling Asynchronous Errors/AsyncErrors.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: Handling Asynchronous Errors 2 | // Proper error handling is crucial in asynchronous programming to prevent crashes. 3 | 4 | // 1. Callbacks: Error-first callback pattern 5 | function fetchWithCallback(callback) { 6 | setTimeout(() => { 7 | const error = new Error('Failed to fetch data'); 8 | callback(error, null); 9 | }, 1000); 10 | } 11 | 12 | console.log('Callback Error Handling:'); 13 | fetchWithCallback((err, data) => { 14 | if (err) { 15 | console.error('Callback Error:', err.message); 16 | return; 17 | } 18 | console.log('Callback Data:', data); 19 | }); 20 | 21 | // 2. Promises: Using .catch() 22 | function fetchWithPromise() { 23 | return new Promise((resolve, reject) => { 24 | setTimeout(() => { 25 | reject(new Error('Failed to fetch data')); 26 | }, 1000); 27 | }); 28 | } 29 | 30 | console.log('Promise Error Handling:'); 31 | fetchWithPromise() 32 | .then(data => console.log('Promise Data:', data)) 33 | .catch(err => console.error('Promise Error:', err.message)); 34 | 35 | // 3. Async/Await: Using try/catch 36 | async function fetchWithAsyncAwait() { 37 | try { 38 | const data = await fetchWithPromise(); 39 | console.log('Async/Await Data:', data); 40 | } catch (err) { 41 | console.error('Async/Await Error:', err.message); 42 | } 43 | } 44 | 45 | console.log('Async/Await Error Handling:'); 46 | fetchWithAsyncAwait(); 47 | 48 | // Expected Output: 49 | // Callback Error Handling: 50 | // Callback Error: Failed to fetch data (after 1 second) 51 | // Promise Error Handling: 52 | // Promise Error: Failed to fetch data (after 1 second) 53 | // Async/Await Error Handling: 54 | // Async/Await Error: Failed to fetch data (after 1 second) 55 | 56 | // To run this in a Node.js environment: 57 | // 1. Save this file as AsyncErrors.js 58 | // 2. Open a terminal and navigate to the file's directory 59 | // 3. Run: node AsyncErrors.js -------------------------------------------------------------------------------- /Node Js Fundamentals/07 Databases/04 CRUD Operations/CRUDOperations.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: CRUD Operations 2 | // CRUD operations (Create, Read, Update, Delete) are fundamental database operations. 3 | 4 | // Note: Requires Sequelize and PostgreSQL driver (npm install sequelize pg pg-hstore) 5 | const { Sequelize, DataTypes } = require('sequelize'); 6 | 7 | const sequelize = new Sequelize('postgres://user:password@localhost:5432/mydatabase', { 8 | dialect: 'postgres' 9 | }); 10 | 11 | const User = sequelize.define('User', { 12 | name: DataTypes.STRING, 13 | email: DataTypes.STRING, 14 | age: DataTypes.INTEGER 15 | }, { 16 | tableName: 'users' 17 | }); 18 | 19 | (async () => { 20 | try { 21 | await sequelize.sync({ force: true }); 22 | console.log('User table created'); 23 | 24 | // Create 25 | const newUser = await User.create({ name: 'Bob', email: 'bob@example.com', age: 30 }); 26 | console.log('Created:', newUser.toJSON()); 27 | 28 | // Read 29 | const users = await User.findAll(); 30 | console.log('Read:', users.map(u => u.toJSON())); 31 | 32 | // Update 33 | await User.update({ age: 31 }, { where: { email: 'bob@example.com' } }); 34 | const updatedUser = await User.findOne({ where: { email: 'bob@example.com' } }); 35 | console.log('Updated:', updatedUser.toJSON()); 36 | 37 | // Delete 38 | await User.destroy({ where: { email: 'bob@example.com' } }); 39 | const remainingUsers = await User.findAll(); 40 | console.log('After Delete:', remainingUsers.map(u => u.toJSON())); 41 | } catch (err) { 42 | console.error('Error:', err.message); 43 | } 44 | })(); 45 | 46 | // To run this in a Node.js environment: 47 | // 1. Ensure PostgreSQL is running locally 48 | // 2. Initialize a project: npm init -y 49 | // 3. Install Sequelize and PostgreSQL driver: npm install sequelize pg pg-hstore 50 | // 4. Update the connection string with your PostgreSQL credentials 51 | // 5. Save this file as CRUDOperations.js 52 | // 6. Run: node CRUDOperations.js 53 | // Note: This code won't execute here due to database restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/06 Express.js Framework/06 REST API Development/RestAPI.js: -------------------------------------------------------------------------------- 1 | // Main Learning Points: REST API Development 2 | // Express is commonly used to build RESTful APIs. 3 | 4 | // Note: Requires Express installation (npm install express) 5 | const express = require('express'); 6 | const app = express(); 7 | 8 | // Middleware to parse JSON 9 | app.use(express.json()); 10 | 11 | // In-memory array to simulate a database 12 | let users = [ 13 | { id: 1, name: 'Alice' }, 14 | { id: 2, name: 'Bob' } 15 | ]; 16 | 17 | // GET: Retrieve all users 18 | app.get('/api/users', (req, res) => { 19 | res.json(users); 20 | }); 21 | 22 | // GET: Retrieve a user by ID 23 | app.get('/api/users/:id', (req, res) => { 24 | const user = users.find(u => u.id === parseInt(req.params.id)); 25 | if (!user) return res.status(404).json({ message: 'User not found' }); 26 | res.json(user); 27 | }); 28 | 29 | // POST: Create a new user 30 | app.post('/api/users', (req, res) => { 31 | const user = { 32 | id: users.length + 1, 33 | name: req.body.name 34 | }; 35 | users.push(user); 36 | res.status(201).json(user); 37 | }); 38 | 39 | // PUT: Update a user 40 | app.put('/api/users/:id', (req, res) => { 41 | const user = users.find(u => u.id === parseInt(req.params.id)); 42 | if (!user) return res.status(404).json({ message: 'User not found' }); 43 | user.name = req.body.name; 44 | res.json(user); 45 | }); 46 | 47 | // DELETE: Delete a user 48 | app.delete('/api/users/:id', (req, res) => { 49 | const userIndex = users.findIndex(u => u.id === parseInt(req.params.id)); 50 | if (userIndex === -1) return res.status(404).json({ message: 'User not found' }); 51 | const deletedUser = users.splice(userIndex, 1); 52 | res.json(deletedUser); 53 | }); 54 | 55 | // Start the server 56 | const PORT = 3005; 57 | app.listen(PORT, () => { 58 | console.log(`Express server running on http://localhost:${PORT}`); 59 | }); 60 | 61 | // To run this in a Node.js environment: 62 | // 1. Initialize a project: npm init -y 63 | // 2. Install Express: npm install express 64 | // 3. Save this file as RestAPI.js 65 | // 4. Run: node RestAPI.js 66 | // 5. Test routes: 67 | // - GET http://localhost:3005/api/users 68 | // - GET http://localhost:3005/api/users/1 69 | // - POST http://localhost:3005/api/users (e.g., curl -X POST -H "Content-Type: application/json" -d '{"name":"Charlie"}' http://localhost:3005/api/users) 70 | // - PUT http://localhost:3005/api/users/1 (e.g., curl -X PUT -H "Content-Type: application/json" -d '{"name":"Alicia"}' http://localhost:3005/api/users/1) 71 | // - DELETE http://localhost:3005/api/users/1 72 | // Note: This code won't execute here due to network restrictions. -------------------------------------------------------------------------------- /Node Js Fundamentals/01 Node.js Basics/index.html: -------------------------------------------------------------------------------- 1 | 41 | 42 | 43 | 44 | 45 | Node.js Basics Demo 46 | 51 | 52 | 53 |
54 |

Node.js Basics Demo

55 |

56 | The following code examples demonstrate core Node.js concepts. Since Node.js cannot be executed in this browser environment, 57 | you'll need to run these files in a Node.js runtime. Follow the instructions in each file to execute them using the Node.js CLI. 58 |

59 | 60 |

1. Understanding the Node.js Runtime

61 |

62 | 
63 |         

2. Event Loop and Non-Blocking I/O

64 |

65 | 
66 |         

3. V8 Engine

67 |

68 | 
69 |         

4. Global Objects (process, buffer, console)

70 |

71 | 
72 |         

5. Node.js CLI and REPL

73 |

74 |     
75 | 76 | 77 | 97 | 98 | -------------------------------------------------------------------------------- /Node Js Fundamentals/03 Asynchronous Programming/index.html: -------------------------------------------------------------------------------- 1 | 41 | 42 | 43 | 44 | 45 | Node.js Asynchronous Programming Demo 46 | 51 | 52 | 53 |
54 |

Node.js Asynchronous Programming Demo

55 |

56 | The following code examples demonstrate asynchronous programming in Node.js. Since Node.js cannot be executed in this browser environment, 57 | you'll need to run these files in a Node.js runtime. Follow the instructions in each file to execute them using the Node.js CLI. 58 |

59 | 60 |

1. Callbacks

61 |

62 | 
63 |         

2. Promises

64 |

65 | 
66 |         

3. Async/Await

67 |

68 | 
69 |         

4. Event Emitters

70 |

71 | 
72 |         

5. Handling Asynchronous Errors

73 |

74 |     
75 | 76 | 77 | 97 | 98 | -------------------------------------------------------------------------------- /Node Js Fundamentals/05 HTTP and Networking/index.html: -------------------------------------------------------------------------------- 1 | 41 | 42 | 43 | 44 | 45 | Node.js HTTP and Networking Demo 46 | 51 | 52 | 53 |
54 |

Node.js HTTP and Networking Demo

55 |

56 | The following code examples demonstrate HTTP and networking concepts in Node.js. Since Node.js cannot be executed in this browser environment 57 | and network calls are restricted, you'll need to run these files in a Node.js runtime. Follow the instructions in each file to execute them using the Node.js CLI. 58 |

59 | 60 |

1. Creating HTTP Servers (http module)

61 |

62 | 
63 |         

2. Handling Requests and Responses

64 |

65 | 
66 |         

3. URL Parsing

67 |

68 | 
69 |         

4. TCP/UDP Servers (net module)

70 |

71 | 
72 |         

5. WebSockets with ws

73 |

74 |     
75 | 76 | 77 | 97 | 98 | -------------------------------------------------------------------------------- /Node Js Fundamentals/04 File System/index.html: -------------------------------------------------------------------------------- 1 | 41 | 42 | 43 | 44 | 45 | Node.js File System Demo 46 | 51 | 52 | 53 |
54 |

Node.js File System Demo

55 |

56 | The following code examples demonstrate file system operations in Node.js. Since Node.js cannot be executed in this browser environment 57 | and file I/O is restricted, you'll need to run these files in a Node.js runtime. Follow the instructions in each file to execute them using the Node.js CLI. 58 |

59 | 60 |

1. Reading and Writing Files (fs module)

61 |

62 | 
63 |         

2. Synchronous vs. Asynchronous Methods

64 |

65 | 
66 |         

3. Streams and Buffers

67 |

68 | 
69 |         

4. File System Watchers

70 |

71 | 
72 |         

5. Directory Management

73 |

74 |     
75 | 76 | 77 | 97 | 98 | -------------------------------------------------------------------------------- /Node Js Fundamentals/02 Modules and Packages/index.html: -------------------------------------------------------------------------------- 1 | 41 | 42 | 43 | 44 | 45 | Node.js Modules and Packages Demo 46 | 51 | 52 | 53 |
54 |

Node.js Modules and Packages Demo

55 |

56 | The following code examples demonstrate Node.js modules and packages. Since Node.js cannot be executed in this browser environment, 57 | you'll need to run these files in a Node.js runtime. Follow the instructions in each file to execute them using the Node.js CLI. 58 |

59 | 60 |

1. CommonJS Modules

61 |

 62 | 
 63 |         

2. ES Modules

64 |

 65 | 
 66 |         

3. require vs. import

67 |

 68 | 
 69 |         

4. Creating and Publishing NPM Packages - Package Code

70 |

 71 | 
 72 |         

4. Creating and Publishing NPM Packages - README

73 |

 74 | 
 75 |         

5. Package.json and Dependency Management

76 |

 77 |     
78 | 79 | 80 | 101 | 102 | -------------------------------------------------------------------------------- /Node Js Fundamentals/09 Performance Optimization/index.html: -------------------------------------------------------------------------------- 1 | 41 | 42 | 43 | 44 | 45 | Node.js Performance Optimization Demo 46 | 51 | 52 | 53 |
54 |

Node.js Performance Optimization Demo

55 |

56 | The following code examples demonstrate performance optimization techniques in Node.js. Since Node.js cannot be executed in this browser environment 57 | and network calls are restricted, you'll need to run these files in a Node.js runtime. Follow the instructions in each file to execute them using the Node.js CLI. 58 |

59 | 60 |

1. Clustering with cluster Module

61 |

 62 | 
 63 |         

2. Load Balancing

64 |

 65 | 
 66 |         

3. Caching with Redis

67 |

 68 | 
 69 |         

4. Rate Limiting

70 |

 71 | 
 72 |         

5. Optimizing Event Loop

73 |

 74 | 
 75 |         

6. Profiling and Debugging

76 |

 77 |     
78 | 79 | 80 | 101 | 102 | -------------------------------------------------------------------------------- /Node Js Fundamentals/08 Authentication and Security/index.html: -------------------------------------------------------------------------------- 1 | 41 | 42 | 43 | 44 | 45 | Node.js Authentication and Security Demo 46 | 51 | 52 | 53 |
54 |

Node.js Authentication and Security Demo

55 |

56 | The following code examples demonstrate authentication and security concepts in Node.js. Since Node.js cannot be executed in this browser environment 57 | and network calls are restricted, you'll need to run these files in a Node.js runtime. Follow the instructions in each file to execute them using the Node.js CLI. 58 |

59 | 60 |

1. JWT and OAuth

61 |

 62 | 
 63 |         

2. Password Hashing with bcrypt

64 |

 65 | 
 66 |         

3. Session Management

67 |

 68 | 
 69 |         

4. Middleware for Authentication

70 |

 71 | 
 72 |         

5. Securing APIs (CORS, Helmet)

73 |

 74 | 
 75 |         

6. Input Validation and Sanitization

76 |

 77 |     
78 | 79 | 80 | 101 | 102 | -------------------------------------------------------------------------------- /Node Js Fundamentals/11 Deployment and DevOps/index.html: -------------------------------------------------------------------------------- 1 | 41 | 42 | 43 | 44 | 45 | Node.js Deployment and DevOps Demo 46 | 51 | 52 | 53 |
54 |

Node.js Deployment and DevOps Demo

55 |

56 | The following code examples demonstrate deployment and DevOps techniques in Node.js. Since Node.js cannot be executed in this browser environment 57 | and network calls are restricted, you'll need to run these in a Node.js runtime with appropriate tools (Docker, PM2, etc.). Follow the instructions in each file. 58 |

59 | 60 |

Application Code: Express App

61 |

 62 | 
 63 |         

1. Environment Variables

64 |

 65 | 
 66 |         

2. PM2 for Process Management

67 |

 68 | 
 69 |         

3. Dockerizing Node.js Apps

70 |

 71 | 
 72 |         

4. CI/CD Pipelines

73 |

 74 | 
 75 |         

5. Cloud Deployment (AWS, Heroku, Vercel)

76 |

 77 | 
 78 |         

6. Logging and Monitoring

79 |

 80 |     
81 | 82 | 83 | 105 | 106 | -------------------------------------------------------------------------------- /Node Js Fundamentals/06 Express.js Framework/index.html: -------------------------------------------------------------------------------- 1 | 41 | 42 | 43 | 44 | 45 | Express.js Framework Demo 46 | 51 | 52 | 53 |
54 |

Express.js Framework Demo

55 |

56 | The following code examples demonstrate Express.js concepts. Since Node.js cannot be executed in this browser environment, 57 | network calls are restricted, and file I/O for templates is not allowed, you'll need to run these files in a Node.js runtime. 58 | Follow the instructions in each file to execute them using the Node.js CLI. 59 |

60 | 61 |

1. Setting Up Express

62 |

 63 | 
 64 |         

2. Routing and Middleware

65 |

 66 | 
 67 |         

3. Request and Response Objects

68 |

 69 | 
 70 |         

4. Template Engines (EJS) - Server Code

71 |

 72 | 
 73 |         

4. Template Engines (EJS) - Example Template

74 |

 75 | 
 76 |         

5. Error Handling

77 |

 78 | 
 79 |         

6. REST API Development

80 |

 81 |     
82 | 83 | 84 | 106 | 107 | -------------------------------------------------------------------------------- /Node Js Fundamentals/07 Databases/index.html: -------------------------------------------------------------------------------- 1 | 41 | 42 | 43 | 44 | 45 | Node.js Databases Demo 46 | 51 | 52 | 53 |
54 |

Node.js Databases Demo

55 |

56 | The following code examples demonstrate database operations in Node.js. Since Node.js cannot be executed in this browser environment 57 | and database operations are restricted, you'll need to run these files in a Node.js runtime with the appropriate database setup. 58 | Follow the instructions in each file to execute them using the Node.js CLI. 59 |

60 | 61 |

1. MongoDB with Mongoose

62 |

 63 | 
 64 |         

2. SQL Databases with Sequelize

65 |

 66 | 
 67 |         

3. Connection Pooling

68 |

 69 | 
 70 |         

4. CRUD Operations

71 |

 72 | 
 73 |         

5. Database Migrations - Setup

74 |

 75 | 
 76 |         

5. Database Migrations - Example Migration

77 |

 78 | 
 79 |         

6. NoSQL vs. SQL Trade-offs

80 |

 81 |     
82 | 83 | 84 | 106 | 107 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🚀 Node.js Interview Preparation 2 | 3 |
4 | Node.js Logo 5 | Express.js 6 | MongoDB 7 | NPM 8 | Jest 9 |
10 |

Your comprehensive guide to mastering Node.js for back-end development interviews

11 | 12 | --- 13 | 14 | ## 📖 Introduction 15 | 16 | Welcome to my Node.js prep for back-end development interviews! 🚀 This repository is your ultimate guide to mastering Node.js, the powerful runtime for building scalable server-side applications. With hands-on coding and interview-focused practice, it’s designed to help you shine in technical interviews and Node.js projects with confidence and expertise. 17 | 18 | ## 🌟 What’s Inside? 19 | 20 | - **Core Node.js Mastery**: Dive into event-driven architecture, modules, and asynchronous programming. 21 | - **Ecosystem Essentials**: Explore Express.js, databases, and authentication. 22 | - **Hands-on Practice**: Solve curated coding challenges with detailed solutions. 23 | - **Interview Question Bank**: Tackle common Node.js questions with concise answers. 24 | - **Performance Optimization**: Learn best practices for efficient, scalable back-end code. 25 | 26 | ## 🔍 Who Is This For? 27 | 28 | - Back-end developers prepping for technical interviews. 29 | - Node.js developers strengthening core and advanced concepts. 30 | - Full-stack developers building server-side skills. 31 | - Software engineers transitioning to Node.js roles. 32 | - Anyone mastering Node.js for modern web applications. 33 | 34 | ## 🗺️ Comprehensive Learning Roadmap 35 | 36 | --- 37 | 38 | ### 🏗️ Core Node.js Foundations 39 | 40 | #### ⚙️ Node.js Basics 41 | - Understanding the Node.js Runtime 42 | - Event Loop and Non-Blocking I/O 43 | - V8 Engine 44 | - Global Objects (`process`, `buffer`, `console`) 45 | - Node.js CLI and REPL 46 | 47 | #### 📦 Modules and Packages 48 | - CommonJS Modules 49 | - ES Modules 50 | - `require` vs. `import` 51 | - Creating and Publishing NPM Packages 52 | - Package.json and Dependency Management 53 | 54 | #### 🔄 Asynchronous Programming 55 | - Callbacks 56 | - Promises 57 | - Async/Await 58 | - Event Emitters 59 | - Handling Asynchronous Errors 60 | 61 | #### 📂 File System 62 | - Reading and Writing Files (`fs` module) 63 | - Synchronous vs. Asynchronous Methods 64 | - Streams and Buffers 65 | - File System Watchers 66 | - Directory Management 67 | 68 | #### 🌐 HTTP and Networking 69 | - Creating HTTP Servers (`http` module) 70 | - Handling Requests and Responses 71 | - URL Parsing 72 | - TCP/UDP Servers (`net` module) 73 | - WebSockets with `ws` 74 | 75 | #### 🛠️ Express.js Framework 76 | - Setting Up Express 77 | - Routing and Middleware 78 | - Request and Response Objects 79 | - Template Engines (e.g., EJS, Pug) 80 | - Error Handling 81 | - REST API Development 82 | 83 | #### 🗄️ Databases 84 | - MongoDB with Mongoose 85 | - SQL Databases with Sequelize/Knex 86 | - Connection Pooling 87 | - CRUD Operations 88 | - Database Migrations 89 | - NoSQL vs. SQL Trade-offs 90 | 91 | #### 🔒 Authentication and Security 92 | - JWT and OAuth 93 | - Password Hashing with `bcrypt` 94 | - Session Management 95 | - Middleware for Authentication 96 | - Securing APIs (CORS, Helmet) 97 | - Input Validation and Sanitization 98 | 99 | #### ⚡ Performance Optimization 100 | - Clustering with `cluster` Module 101 | - Load Balancing 102 | - Caching with Redis 103 | - Rate Limiting 104 | - Optimizing Event Loop 105 | - Profiling and Debugging 106 | 107 | #### 🧪 Testing 108 | - Unit Testing with Jest 109 | - Integration Testing 110 | - Mocking Dependencies 111 | - API Testing with Supertest 112 | - Code Coverage 113 | - End-to-End Testing 114 | 115 | #### 📡 Deployment and DevOps 116 | - Environment Variables 117 | - PM2 for Process Management 118 | - Dockerizing Node.js Apps 119 | - CI/CD Pipelines 120 | - Cloud Deployment (AWS, Heroku, Vercel) 121 | - Logging and Monitoring 122 | 123 | #### 🧬 Advanced Concepts 124 | - Microservices Architecture 125 | - GraphQL with Apollo 126 | - Serverless Node.js (AWS Lambda) 127 | - Worker Threads 128 | - Child Processes 129 | - Building CLI Tools 130 | 131 | --- 132 | 133 | ## 💡 Why Master Node.js for Back-End Development? 134 | 135 | Node.js is a game-changer for server-side development, and here’s why: 136 | 1. **Scalability**: Handles high concurrency with ease. 137 | 2. **JavaScript Everywhere**: Unified language for front-end and back-end. 138 | 3. **Rich Ecosystem**: Massive NPM library for rapid development. 139 | 4. **Industry Demand**: A must-have skill for 6 LPA+ back-end roles. 140 | 5. **Community Support**: Backed by a thriving developer network. 141 | 142 | This repo is my roadmap to mastering Node.js for technical interviews and back-end careers—let’s build that skill set together! 143 | 144 | ## 📆 Study Plan 145 | 146 | - **Week 1-2**: Core Node.js Fundamentals and Asynchronous Programming 147 | - **Week 3-4**: Express.js, Databases, and APIs 148 | 149 | ## 🤝 Contributions 150 | 151 | Love to collaborate? Here’s how! 🌟 152 | 1. Fork the repository. 153 | 2. Create a feature branch (`git checkout -b feature/amazing-addition`). 154 | 3. Commit your changes (`git commit -m 'Add some amazing content'`). 155 | 4. Push to the branch (`git push origin feature/amazing-addition`). 156 | 5. Open a Pull Request. 157 | 158 | --- 159 | 160 |
161 |

Happy Learning and Good Luck with Your Interviews! ✨

162 |
-------------------------------------------------------------------------------- /Node Js Interview Questions/README.md: -------------------------------------------------------------------------------- 1 | # Node.js Interview Questions for AI/ML Roles 2 | 3 | This README provides **170 Node.js interview questions** tailored for AI/ML students preparing for technical interviews, focusing on Node.js’s role in building scalable back-end services for AI/ML applications (e.g., APIs for model inference, data processing pipelines, and real-time prediction servers). The questions are categorized into **Node.js Basics**, **Modules**, **File System**, **HTTP Servers**, **Middleware**, **Databases**, **Performance Optimization**, **Testing**, and **Integration with AI/ML**. Each category is divided into **Basic**, **Intermediate**, and **Advanced** levels, with practical code snippets using Node.js and JavaScript. This resource supports candidates aiming for roles that combine back-end development with AI/ML workflows, such as creating APIs for machine learning models or handling large-scale data processing. 4 | 5 | ## Node.js Basics 6 | 7 | ### Basic 8 | 1. **What is Node.js, and why is it used in back-end development?** 9 | Node.js is a runtime for executing JavaScript outside the browser, using the V8 engine. 10 | ```javascript 11 | console.log("Hello, Node.js!"); 12 | ``` 13 | 14 | 2. **What is the event loop in Node.js?** 15 | Handles asynchronous operations via a single-threaded loop. 16 | ```javascript 17 | setTimeout(() => console.log("Delayed"), 1000); 18 | console.log("Immediate"); 19 | ``` 20 | 21 | 3. **How do you run a Node.js script?** 22 | Uses the `node` command. 23 | ```javascript 24 | // script.js 25 | console.log("Running Node.js script"); 26 | ``` 27 | ```bash 28 | node script.js 29 | ``` 30 | 31 | 4. **What is the difference between synchronous and asynchronous code in Node.js?** 32 | Sync blocks execution, async does not. 33 | ```javascript 34 | // Sync 35 | console.log("Sync"); 36 | // Async 37 | setImmediate(() => console.log("Async")); 38 | ``` 39 | 40 | 5. **How do you handle errors in Node.js?** 41 | Uses try-catch for sync, callbacks for async. 42 | ```javascript 43 | try { 44 | throw new Error("Sync error"); 45 | } catch (err) { 46 | console.error(err.message); 47 | } 48 | ``` 49 | 50 | 6. **How do you visualize Node.js execution time?** 51 | Plots execution durations. 52 | ```python 53 | import matplotlib.pyplot as plt 54 | def plot_execution_times(times): 55 | plt.plot(times, 'o-', label='Execution Time (ms)') 56 | plt.title('Node.js Execution Performance') 57 | plt.savefig('execution_times.png') 58 | ``` 59 | 60 | #### Intermediate 61 | 7. **Write a function to handle asynchronous operations.** 62 | Uses callbacks. 63 | ```javascript 64 | function asyncTask(callback) { 65 | setTimeout(() => callback(null, "Done"), 1000); 66 | } 67 | asyncTask((err, result) => console.log(result)); 68 | ``` 69 | 70 | 8. **How do you use Promises in Node.js?** 71 | Handles async with resolve/reject. 72 | ```javascript 73 | const promise = new Promise((resolve) => setTimeout(() => resolve("Success"), 1000)); 74 | promise.then(result => console.log(result)); 75 | ``` 76 | 77 | 9. **Write a function to chain asynchronous tasks.** 78 | Uses async/await. 79 | ```javascript 80 | async function chainTasks() { 81 | const result1 = await new Promise(r => setTimeout(() => r("Task 1"), 1000)); 82 | const result2 = await new Promise(r => setTimeout(() => r("Task 2"), 1000)); 83 | console.log(result1, result2); 84 | } 85 | chainTasks(); 86 | ``` 87 | 88 | 10. **How do you manage environment variables in Node.js?** 89 | Uses `process.env`. 90 | ```javascript 91 | console.log(process.env.NODE_ENV || "development"); 92 | ``` 93 | 94 | 11. **Write a function to log Node.js process details.** 95 | Accesses process info. 96 | ```javascript 97 | function logProcess() { 98 | console.log(`PID: ${process.pid}, Version: ${process.version}`); 99 | } 100 | logProcess(); 101 | ``` 102 | 103 | 12. **How do you exit a Node.js process?** 104 | Uses `process.exit`. 105 | ```javascript 106 | console.log("Exiting..."); 107 | process.exit(0); 108 | ``` 109 | 110 | #### Advanced 111 | 13. **Write a function to handle uncaught exceptions.** 112 | Uses `process.on`. 113 | ```javascript 114 | process.on("uncaughtException", (err) => console.error("Uncaught:", err.message)); 115 | throw new Error("Test error"); 116 | ``` 117 | 118 | 14. **How do you implement a worker thread in Node.js?** 119 | Uses `worker_threads`. 120 | ```javascript 121 | const { Worker, isMainThread, parentPort } = require("worker_threads"); 122 | if (isMainThread) { 123 | const worker = new Worker(__filename); 124 | worker.on("message", msg => console.log(msg)); 125 | } else { 126 | parentPort.postMessage("Hello from worker"); 127 | } 128 | ``` 129 | 130 | 15. **Write a function to monitor Node.js memory usage.** 131 | Logs memory stats. 132 | ```javascript 133 | function monitorMemory() { 134 | const used = process.memoryUsage(); 135 | console.log(`Heap: ${used.heapUsed / 1024 / 1024} MB`); 136 | } 137 | monitorMemory(); 138 | ``` 139 | 140 | 16. **How do you handle async errors in Node.js?** 141 | Uses try-catch with async/await. 142 | ```javascript 143 | async function handleAsyncError() { 144 | try { 145 | throw new Error("Async error"); 146 | } catch (err) { 147 | console.error(err.message); 148 | } 149 | } 150 | handleAsyncError(); 151 | ``` 152 | 153 | 17. **Write a function to benchmark Node.js performance.** 154 | Measures execution time. 155 | ```javascript 156 | function benchmark(fn) { 157 | const start = performance.now(); 158 | fn(); 159 | console.log(`Time: ${performance.now() - start}ms`); 160 | } 161 | benchmark(() => Array(1000).fill(0).map(Math.sqrt)); 162 | ``` 163 | 164 | 18. **How do you use Node.js clusters for scalability?** 165 | Distributes workload across CPUs. 166 | ```javascript 167 | const cluster = require("cluster"); 168 | const http = require("http"); 169 | if (cluster.isMaster) { 170 | cluster.fork(); 171 | } else { 172 | http.createServer((req, res) => res.end("Worker")).listen(3000); 173 | } 174 | ``` 175 | 176 | ## Modules 177 | 178 | ### Basic 179 | 19. **What are Node.js modules?** 180 | Reusable code units. 181 | ```javascript 182 | const myModule = { 183 | sayHello: () => console.log("Hello") 184 | }; 185 | module.exports = myModule; 186 | ``` 187 | 188 | 20. **How do you create a CommonJS module?** 189 | Uses `module.exports`. 190 | ```javascript 191 | // math.js 192 | module.exports = { 193 | add: (a, b) => a + b 194 | }; 195 | ``` 196 | 197 | 21. **How do you import modules in Node.js?** 198 | Uses `require`. 199 | ```javascript 200 | const math = require("./math"); 201 | console.log(math.add(2, 3)); 202 | ``` 203 | 204 | 22. **What is ES Modules in Node.js?** 205 | Uses `import/export` syntax. 206 | ```javascript 207 | // math.mjs 208 | export const add = (a, b) => a + b; 209 | ``` 210 | 211 | 23. **How do you use ES Modules?** 212 | Imports with `import`. 213 | ```javascript 214 | import { add } from "./math.mjs"; 215 | console.log(add(2, 3)); 216 | ``` 217 | 218 | 24. **How do you visualize module dependencies?** 219 | Plots dependency graph (mock). 220 | ```python 221 | import matplotlib.pyplot as plt 222 | def plot_dependencies(modules): 223 | plt.bar(modules, range(len(modules)), label='Dependencies') 224 | plt.title('Module Dependencies') 225 | plt.savefig('module_dependencies.png') 226 | ``` 227 | 228 | #### Intermediate 229 | 25. **Write a function to create a reusable module.** 230 | Exports utility functions. 231 | ```javascript 232 | // utils.js 233 | module.exports = { 234 | square: n => n * n 235 | }; 236 | ``` 237 | 238 | 26. **How do you handle module caching in Node.js?** 239 | Modules are cached after first load. 240 | ```javascript 241 | const mod = require("./utils"); 242 | console.log(mod.square(4)); // Cached 243 | ``` 244 | 245 | 27. **Write a function to dynamically import modules.** 246 | Uses dynamic `import()`. 247 | ```javascript 248 | async function loadModule() { 249 | const { add } = await import("./math.mjs"); 250 | console.log(add(2, 3)); 251 | } 252 | loadModule(); 253 | ``` 254 | 255 | 28. **How do you create a module with default exports?** 256 | Uses `export default`. 257 | ```javascript 258 | // logger.mjs 259 | export default function log(msg) { 260 | console.log(msg); 261 | } 262 | ``` 263 | 264 | 29. **Write a function to manage module dependencies.** 265 | Resolves dependency order. 266 | ```javascript 267 | function loadDependencies(mods) { 268 | mods.forEach(mod => require(mod)); 269 | console.log("Dependencies loaded"); 270 | } 271 | loadDependencies(["./math", "./utils"]); 272 | ``` 273 | 274 | 30. **How do you use third-party modules?** 275 | Installs via npm and imports. 276 | ```javascript 277 | const lodash = require("lodash"); 278 | console.log(lodash.sum([1, 2, 3])); 279 | ``` 280 | 281 | #### Advanced 282 | 31. **Write a function to create a private module scope.** 283 | Uses IIFE for encapsulation. 284 | ```javascript 285 | const myModule = (() => { 286 | const privateVar = "secret"; 287 | return { 288 | getSecret: () => privateVar 289 | }; 290 | })(); 291 | console.log(myModule.getSecret()); 292 | ``` 293 | 294 | 32. **How do you optimize module loading?** 295 | Minimizes dependencies. 296 | ```javascript 297 | const { add } = require("./math"); // Selective import 298 | console.log(add(2, 3)); 299 | ``` 300 | 301 | 33. **Write a function to audit module performance.** 302 | Measures load time. 303 | ```javascript 304 | function auditModule(mod) { 305 | const start = performance.now(); 306 | require(mod); 307 | console.log(`Load time: ${performance.now() - start}ms`); 308 | } 309 | auditModule("./math"); 310 | ``` 311 | 312 | 34. **How do you handle circular dependencies?** 313 | Refactors to avoid cycles. 314 | ```javascript 315 | // a.js 316 | module.exports = { fn: () => require("./b").fn() }; 317 | // b.js 318 | module.exports = { fn: () => "B" }; 319 | ``` 320 | 321 | 35. **Write a function to mock modules for testing.** 322 | Overrides module exports. 323 | ```javascript 324 | jest.mock("./math", () => ({ 325 | add: jest.fn().mockReturnValue(5) 326 | })); 327 | const math = require("./math"); 328 | console.log(math.add(2, 3)); // 5 329 | ``` 330 | 331 | 36. **How do you use Node.js native addons?** 332 | Integrates C++ modules (mock). 333 | ```javascript 334 | const addon = require("./build/Release/addon"); 335 | console.log(addon.hello()); // Mock 336 | ``` 337 | 338 | ## File System 339 | 340 | ### Basic 341 | 37. **How do you read a file in Node.js?** 342 | Uses `fs.readFile`. 343 | ```javascript 344 | const fs = require("fs"); 345 | fs.readFile("data.txt", "utf8", (err, data) => console.log(data)); 346 | ``` 347 | 348 | 38. **How do you write to a file in Node.js?** 349 | Uses `fs.writeFile`. 350 | ```javascript 351 | const fs = require("fs"); 352 | fs.writeFile("output.txt", "Hello", err => console.log(err ? "Error" : "Written")); 353 | ``` 354 | 355 | 39. **How do you check if a file exists?** 356 | Uses `fs.access`. 357 | ```javascript 358 | const fs = require("fs"); 359 | fs.access("data.txt", fs.constants.F_OK, err => console.log(err ? "Missing" : "Exists")); 360 | ``` 361 | 362 | 40. **How do you create a directory?** 363 | Uses `fs.mkdir`. 364 | ```javascript 365 | const fs = require("fs"); 366 | fs.mkdir("newDir", err => console.log(err ? "Error" : "Created")); 367 | ``` 368 | 369 | 41. **How do you delete a file?** 370 | Uses `fs.unlink`. 371 | ```javascript 372 | const fs = require("fs"); 373 | fs.unlink("output.txt", err => console.log(err ? "Error" : "Deleted")); 374 | ``` 375 | 376 | 42. **How do you visualize file system operations?** 377 | Plots operation times. 378 | ```python 379 | import matplotlib.pyplot as plt 380 | def plot_fs_operations(times): 381 | plt.plot(times, 'o-', label='FS Operation Time (ms)') 382 | plt.title('File System Performance') 383 | plt.savefig('fs_operations.png') 384 | ``` 385 | 386 | #### Intermediate 387 | 43. **Write a function to read files synchronously.** 388 | Uses `fs.readFileSync`. 389 | ```javascript 390 | const fs = require("fs"); 391 | function readSync(path) { 392 | try { 393 | return fs.readFileSync(path, "utf8"); 394 | } catch (err) { 395 | console.error(err); 396 | } 397 | } 398 | console.log(readSync("data.txt")); 399 | ``` 400 | 401 | 44. **How do you stream large files in Node.js?** 402 | Uses `fs.createReadStream`. 403 | ```javascript 404 | const fs = require("fs"); 405 | const stream = fs.createReadStream("large.txt"); 406 | stream.on("data", chunk => console.log(chunk.toString())); 407 | ``` 408 | 409 | 45. **Write a function to copy files.** 410 | Uses `fs.copyFile`. 411 | ```javascript 412 | const fs = require("fs"); 413 | function copyFile(src, dest) { 414 | fs.copyFile(src, dest, err => console.log(err ? "Error" : "Copied")); 415 | } 416 | copyFile("source.txt", "dest.txt"); 417 | ``` 418 | 419 | 46. **How do you watch for file changes?** 420 | Uses `fs.watch`. 421 | ```javascript 422 | const fs = require("fs"); 423 | fs.watch("data.txt", (event, filename) => console.log(`${filename} changed`)); 424 | ``` 425 | 426 | 47. **Write a function to list directory contents.** 427 | Uses `fs.readdir`. 428 | ```javascript 429 | const fs = require("fs"); 430 | function listDir(path) { 431 | fs.readdir(path, (err, files) => console.log(files)); 432 | } 433 | listDir("."); 434 | ``` 435 | 436 | 48. **How do you handle file permissions?** 437 | Uses `fs.chmod`. 438 | ```javascript 439 | const fs = require("fs"); 440 | fs.chmod("data.txt", 0o644, err => console.log(err ? "Error" : "Permissions set")); 441 | ``` 442 | 443 | #### Advanced 444 | 49. **Write a function to recursively read directories.** 445 | Uses `fs.readdir` recursively. 446 | ```javascript 447 | const fs = require("fs").promises; 448 | async function readDirRecursive(path) { 449 | const entries = await fs.readdir(path, { withFileTypes: true }); 450 | for (const entry of entries) { 451 | const fullPath = `${path}/${entry.name}`; 452 | console.log(fullPath); 453 | if (entry.isDirectory()) await readDirRecursive(fullPath); 454 | } 455 | } 456 | readDirRecursive("."); 457 | ``` 458 | 459 | 50. **How do you optimize file system operations?** 460 | Batches operations. 461 | ```javascript 462 | const fs = require("fs").promises; 463 | async function batchWrite(files) { 464 | await Promise.all( 465 | files.map(([path, content]) => fs.writeFile(path, content)) 466 | ); 467 | console.log("Batch complete"); 468 | } 469 | batchWrite([["a.txt", "A"], ["b.txt", "B"]]); 470 | ``` 471 | 472 | 51. **Write a function to monitor file system performance.** 473 | Logs operation time. 474 | ```javascript 475 | const fs = require("fs"); 476 | function monitorFS(path) { 477 | const start = performance.now(); 478 | fs.readFile(path, () => console.log(`Read time: ${performance.now() - start}ms`)); 479 | } 480 | monitorFS("data.txt"); 481 | ``` 482 | 483 | 52. **How do you handle large file uploads?** 484 | Uses streams. 485 | ```javascript 486 | const fs = require("fs"); 487 | const http = require("http"); 488 | http.createServer((req, res) => { 489 | req.pipe(fs.createWriteStream("upload.txt")); 490 | req.on("end", () => res.end("Uploaded")); 491 | }).listen(3000); 492 | ``` 493 | 494 | 53. **Write a function to compress files.** 495 | Uses `zlib`. 496 | ```javascript 497 | const fs = require("fs"); 498 | const zlib = require("zlib"); 499 | fs.createReadStream("data.txt") 500 | .pipe(zlib.createGzip()) 501 | .pipe(fs.createWriteStream("data.txt.gz")); 502 | ``` 503 | 504 | 54. **How do you secure file system access?** 505 | Restricts permissions. 506 | ```javascript 507 | const fs = require("fs"); 508 | fs.chmod("sensitive.txt", 0o600, err => console.log(err ? "Error" : "Secured")); 509 | ``` 510 | 511 | ## HTTP Servers 512 | 513 | ### Basic 514 | 55. **How do you create an HTTP server in Node.js?** 515 | Uses `http.createServer`. 516 | ```javascript 517 | const http = require("http"); 518 | http.createServer((req, res) => res.end("Hello")).listen(3000); 519 | ``` 520 | 521 | 56. **How do you handle HTTP GET requests?** 522 | Checks `req.method`. 523 | ```javascript 524 | const http = require("http"); 525 | http.createServer((req, res) => { 526 | if (req.method === "GET") res.end("GET request"); 527 | }).listen(3000); 528 | ``` 529 | 530 | 57. **How do you serve static files?** 531 | Reads and sends files. 532 | ```javascript 533 | const http = require("http"); 534 | const fs = require("fs"); 535 | http.createServer((req, res) => { 536 | fs.readFile("index.html", (err, data) => res.end(data)); 537 | }).listen(3000); 538 | ``` 539 | 540 | 58. **How do you parse URL parameters?** 541 | Uses `url.parse`. 542 | ```javascript 543 | const http = require("http"); 544 | const url = require("url"); 545 | http.createServer((req, res) => { 546 | const params = url.parse(req.url, true).query; 547 | res.end(JSON.stringify(params)); 548 | }).listen(3000); 549 | ``` 550 | 551 | 59. **How do you set HTTP headers?** 552 | Uses `res.setHeader`. 553 | ```javascript 554 | const http = require("http"); 555 | http.createServer((req, res) => { 556 | res.setHeader("Content-Type", "application/json"); 557 | res.end('{"message":"Hello"}'); 558 | }).listen(3000); 559 | ``` 560 | 561 | 60. **How do you visualize HTTP request metrics?** 562 | Plots request times. 563 | ```python 564 | import matplotlib.pyplot as plt 565 | def plot_request_metrics(times): 566 | plt.plot(times, 'o-', label='Request Time (ms)') 567 | plt.title('HTTP Request Performance') 568 | plt.savefig('request_metrics.png') 569 | ``` 570 | 571 | #### Intermediate 572 | 61. **Write a function to handle POST requests.** 573 | Parses request body. 574 | ```javascript 575 | const http = require("http"); 576 | http.createServer((req, res) => { 577 | if (req.method === "POST") { 578 | let body = ""; 579 | req.on("data", chunk => (body += chunk)); 580 | req.on("end", () => res.end(body)); 581 | } 582 | }).listen(3000); 583 | ``` 584 | 585 | 62. **How do you create a REST API in Node.js?** 586 | Defines endpoints. 587 | ```javascript 588 | const http = require("http"); 589 | http.createServer((req, res) => { 590 | if (req.url === "/api" && req.method === "GET") { 591 | res.end('{"data":"API"}'); 592 | } 593 | }).listen(3000); 594 | ``` 595 | 596 | 63. **Write a function to route HTTP requests.** 597 | Uses URL patterns. 598 | ```javascript 599 | const http = require("http"); 600 | function route(req, res) { 601 | const routes = { 602 | "/home": () => "Home", 603 | "/about": () => "About" 604 | }; 605 | res.end(routes[req.url] ? routes[req.url]() : "Not Found"); 606 | } 607 | http.createServer(route).listen(3000); 608 | ``` 609 | 610 | 64. **How do you handle CORS in Node.js?** 611 | Sets CORS headers. 612 | ```javascript 613 | const http = require("http"); 614 | http.createServer((req, res) => { 615 | res.setHeader("Access-Control-Allow-Origin", "*"); 616 | res.end("CORS enabled"); 617 | }).listen(3000); 618 | ``` 619 | 620 | 65. **Write a function to stream HTTP responses.** 621 | Uses `res.write`. 622 | ```javascript 623 | const http = require("http"); 624 | http.createServer((req, res) => { 625 | res.write("Streaming..."); 626 | setTimeout(() => res.end("Done"), 1000); 627 | }).listen(3000); 628 | ``` 629 | 630 | 66. **How do you handle query parameters in APIs?** 631 | Parses query strings. 632 | ```javascript 633 | const http = require("http"); 634 | const url = require("url"); 635 | http.createServer((req, res) => { 636 | const { id } = url.parse(req.url, true).query; 637 | res.end(`ID: ${id}`); 638 | }).listen(3000); 639 | ``` 640 | 641 | #### Advanced 642 | 67. **Write a function to implement rate limiting.** 643 | Restricts request frequency. 644 | ```javascript 645 | const http = require("http"); 646 | const requests = new Map(); 647 | http.createServer((req, res) => { 648 | const ip = req.socket.remoteAddress; 649 | const count = (requests.get(ip) || 0) + 1; 650 | requests.set(ip, count); 651 | if (count > 5) res.end("Rate limit exceeded"); 652 | else res.end("OK"); 653 | }).listen(3000); 654 | ``` 655 | 656 | 68. **How do you secure HTTP servers?** 657 | Uses HTTPS. 658 | ```javascript 659 | const https = require("https"); 660 | const fs = require("fs"); 661 | const options = { 662 | key: fs.readFileSync("key.pem"), 663 | cert: fs.readFileSync("cert.pem") 664 | }; 665 | https.createServer(options, (req, res) => res.end("Secure")).listen(3000); 666 | ``` 667 | 668 | 69. **Write a function to monitor API performance.** 669 | Logs response time. 670 | ```javascript 671 | const http = require("http"); 672 | http.createServer((req, res) => { 673 | const start = performance.now(); 674 | res.on("finish", () => console.log(`Response time: ${performance.now() - start}ms`)); 675 | res.end("OK"); 676 | }).listen(3000); 677 | ``` 678 | 679 | 70. **How do you implement WebSockets in Node.js?** 680 | Uses `ws` module. 681 | ```javascript 682 | const WebSocket = require("ws"); 683 | const wss = new WebSocket.Server({ port: 3000 }); 684 | wss.on("connection", ws => ws.send("Connected")); 685 | ``` 686 | 687 | 71. **Write a function to handle API versioning.** 688 | Uses URL prefixes. 689 | ```javascript 690 | const http = require("http"); 691 | http.createServer((req, res) => { 692 | if (req.url.startsWith("/v1")) res.end("Version 1"); 693 | else if (req.url.startsWith("/v2")) res.end("Version 2"); 694 | else res.end("No version"); 695 | }).listen(3000); 696 | ``` 697 | 698 | 72. **How do you optimize HTTP server performance?** 699 | Uses connection pooling. 700 | ```javascript 701 | const http = require("http"); 702 | const agent = new http.Agent({ maxSockets: 10 }); 703 | http.createServer((req, res) => res.end("Optimized")).listen(3000, { agent }); 704 | ``` 705 | 706 | ## Middleware 707 | 708 | ### Basic 709 | 73. **What is middleware in Node.js?** 710 | Functions that process requests. 711 | ```javascript 712 | const express = require("express"); 713 | const app = express(); 714 | app.use((req, res, next) => { 715 | console.log("Middleware"); 716 | next(); 717 | }); 718 | app.listen(3000); 719 | ``` 720 | 721 | 74. **How do you create custom middleware?** 722 | Defines request handlers. 723 | ```javascript 724 | const express = require("express"); 725 | const app = express(); 726 | app.use((req, res, next) => { 727 | req.custom = "Custom"; 728 | next(); 729 | }); 730 | app.get("/", (req, res) => res.send(req.custom)); 731 | app.listen(3000); 732 | ``` 733 | 734 | 75. **How do you handle errors in middleware?** 735 | Uses error-handling middleware. 736 | ```javascript 737 | const express = require("express"); 738 | const app = express(); 739 | app.use((err, req, res, next) => { 740 | res.status(500).send("Error"); 741 | }); 742 | app.listen(3000); 743 | ``` 744 | 745 | 76. **How do you log requests in middleware?** 746 | Logs request details. 747 | ```javascript 748 | const express = require("express"); 749 | const app = express(); 750 | app.use((req, res, next) => { 751 | console.log(`${req.method} ${req.url}`); 752 | next(); 753 | }); 754 | app.listen(3000); 755 | ``` 756 | 757 | 77. **How do you use third-party middleware?** 758 | Integrates packages like `morgan`. 759 | ```javascript 760 | const express = require("express"); 761 | const morgan = require("morgan"); 762 | const app = express(); 763 | app.use(morgan("dev")); 764 | app.listen(3000); 765 | ``` 766 | 767 | 78. **How do you visualize middleware performance?** 768 | Plots execution times. 769 | ```python 770 | import matplotlib.pyplot as plt 771 | def plot_middleware_times(times): 772 | plt.plot(times, 'o-', label='Middleware Time (ms)') 773 | plt.title('Middleware Performance') 774 | plt.savefig('middleware_times.png') 775 | ``` 776 | 777 | #### Intermediate 778 | 79. **Write a function to authenticate requests in middleware.** 779 | Checks tokens. 780 | ```javascript 781 | const express = require("express"); 782 | const app = express(); 783 | app.use((req, res, next) => { 784 | if (req.headers.authorization === "Bearer token") next(); 785 | else res.status(401).send("Unauthorized"); 786 | }); 787 | app.get("/", (req, res) => res.send("Authenticated")); 788 | app.listen(3000); 789 | ``` 790 | 791 | 80. **How do you implement rate-limiting middleware?** 792 | Limits requests per IP. 793 | ```javascript 794 | const express = require("express"); 795 | const app = express(); 796 | const requests = new Map(); 797 | app.use((req, res, next) => { 798 | const ip = req.ip; 799 | const count = (requests.get(ip) || 0) + 1; 800 | requests.set(ip, count); 801 | if (count > 5) res.status(429).send("Too Many Requests"); 802 | else next(); 803 | }); 804 | app.listen(3000); 805 | ``` 806 | 807 | 81. **Write a function to parse JSON in middleware.** 808 | Handles JSON payloads. 809 | ```javascript 810 | const express = require("express"); 811 | const app = express(); 812 | app.use(express.json()); 813 | app.post("/", (req, res) => res.send(req.body)); 814 | app.listen(3000); 815 | ``` 816 | 817 | 82. **How do you chain middleware?** 818 | Executes in sequence. 819 | ```javascript 820 | const express = require("express"); 821 | const app = express(); 822 | app.use((req, res, next) => { 823 | req.data = "Step 1"; 824 | next(); 825 | }); 826 | app.use((req, res, next) => { 827 | req.data += " Step 2"; 828 | next(); 829 | }); 830 | app.get("/", (req, res) => res.send(req.data)); 831 | app.listen(3000); 832 | ``` 833 | 834 | 83. **Write a function to compress responses.** 835 | Uses `compression` middleware. 836 | ```javascript 837 | const express = require("express"); 838 | const compression = require("compression"); 839 | const app = express(); 840 | app.use(compression()); 841 | app.get("/", (req, res) => res.send("Compressed")); 842 | app.listen(3000); 843 | ``` 844 | 845 | 84. **How do you handle middleware for specific routes?** 846 | Applies to route subsets. 847 | ```javascript 848 | const express = require("express"); 849 | const app = express(); 850 | const admin = (req, res, next) => { 851 | req.admin = true; 852 | next(); 853 | }; 854 | app.get("/admin", admin, (req, res) => res.send("Admin")); 855 | app.listen(3000); 856 | ``` 857 | 858 | #### Advanced 859 | 85. **Write a function to implement custom middleware for AI APIs.** 860 | Validates ML inputs. 861 | ```javascript 862 | const express = require("express"); 863 | const app = express(); 864 | app.use((req, res, next) => { 865 | if (req.body.data && Array.isArray(req.body.data)) next(); 866 | else res.status(400).send("Invalid ML input"); 867 | }); 868 | app.post("/predict", (req, res) => res.send("Valid")); 869 | app.listen(3000); 870 | ``` 871 | 872 | 86. **How do you optimize middleware performance?** 873 | Minimizes overhead. 874 | ```javascript 875 | const express = require("express"); 876 | const app = express(); 877 | app.use((req, res, next) => { 878 | next(); // Skip heavy logic 879 | }); 880 | app.listen(3000); 881 | ``` 882 | 883 | 87. **Write a function to monitor middleware execution.** 884 | Logs execution time. 885 | ```javascript 886 | const express = require("express"); 887 | const app = express(); 888 | app.use((req, res, next) => { 889 | const start = performance.now(); 890 | res.on("finish", () => console.log(`Middleware time: ${performance.now() - start}ms`)); 891 | next(); 892 | }); 893 | app.listen(3000); 894 | ``` 895 | 896 | 88. **How do you implement middleware for WebSocket connections?** 897 | Validates WebSocket requests. 898 | ```javascript 899 | const WebSocket = require("ws"); 900 | const wss = new WebSocket.Server({ port: 3000 }); 901 | wss.on("connection", (ws, req) => { 902 | if (req.headers["x-token"]) ws.send("Authenticated"); 903 | else ws.close(); 904 | }); 905 | ``` 906 | 907 | 89. **Write a function to audit middleware security.** 908 | Checks for vulnerabilities. 909 | ```javascript 910 | const express = require("express"); 911 | const app = express(); 912 | function auditMiddleware(req, res, next) { 913 | if (!req.headers["x-api-key"]) { 914 | console.log("Missing API key"); 915 | res.status(401).send("Unauthorized"); 916 | } else { 917 | next(); 918 | } 919 | } 920 | app.use(auditMiddleware); 921 | app.get("/", (req, res) => res.send("Secure")); 922 | app.listen(3000); 923 | ``` 924 | 925 | 90. **How do you test middleware?** 926 | Mocks requests. 927 | ```javascript 928 | const express = require("express"); 929 | const app = express(); 930 | app.use((req, res, next) => { 931 | req.test = "Tested"; 932 | next(); 933 | }); 934 | const mockReq = { headers: {} }; 935 | const mockRes = {}; 936 | const mockNext = () => console.log(mockReq.test); // Tested 937 | app._router.handle(mockReq, mockRes, mockNext); 938 | ``` 939 | 940 | ## Databases 941 | 942 | ### Basic 943 | 91. **How do you connect to a database in Node.js?** 944 | Uses MongoDB driver (mock). 945 | ```javascript 946 | const { MongoClient } = require("mongodb"); 947 | async function connectDB() { 948 | const client = new MongoClient("mongodb://localhost:27017"); 949 | await client.connect(); 950 | console.log("Connected"); 951 | await client.close(); 952 | } 953 | connectDB(); 954 | ``` 955 | 956 | 92. **How do you query a database?** 957 | Uses MongoDB find. 958 | ```javascript 959 | const { MongoClient } = require("mongodb"); 960 | async function queryDB() { 961 | const client = new MongoClient("mongodb://localhost:27017"); 962 | await client.connect(); 963 | const db = client.db("test"); 964 | const data = await db.collection("users").findOne({ name: "John" }); 965 | console.log(data); 966 | await client.close(); 967 | } 968 | queryDB(); 969 | ``` 970 | 971 | 93. **How do you insert data into a database?** 972 | Uses MongoDB insert. 973 | ```javascript 974 | const { MongoClient } = require("mongodb"); 975 | async function insertDB() { 976 | const client = new MongoClient("mongodb://localhost:27017"); 977 | await client.connect(); 978 | const db = client.db("test"); 979 | await db.collection("users").insertOne({ name: "John" }); 980 | console.log("Inserted"); 981 | await client.close(); 982 | } 983 | insertDB(); 984 | ``` 985 | 986 | 94. **How do you update database records?** 987 | Uses MongoDB update. 988 | ```javascript 989 | const { MongoClient } = require("mongodb"); 990 | async function updateDB() { 991 | const client = new MongoClient("mongodb://localhost:27017"); 992 | await client.connect(); 993 | const db = client.db("test"); 994 | await db.collection("users").updateOne({ name: "John" }, { $set: { age: 30 } }); 995 | console.log("Updated"); 996 | await client.close(); 997 | } 998 | updateDB(); 999 | ``` 1000 | 1001 | 95. **How do you delete database records?** 1002 | Uses MongoDB delete. 1003 | ```javascript 1004 | const { MongoClient } = require("mongodb"); 1005 | async function deleteDB() { 1006 | const client = new MongoClient("mongodb://localhost:27017"); 1007 | await client.connect(); 1008 | const db = client.db("test"); 1009 | await db.collection("users").deleteOne({ name: "John" }); 1010 | console.log("Deleted"); 1011 | await client.close(); 1012 | } 1013 | deleteDB(); 1014 | ``` 1015 | 1016 | 96. **How do you visualize database query performance?** 1017 | Plots query times. 1018 | ```python 1019 | import matplotlib.pyplot as plt 1020 | def plot_query_performance(times): 1021 | plt.plot(times, 'o-', label='Query Time (ms)') 1022 | plt.title('Database Query Performance') 1023 | plt.savefig('query_performance.png') 1024 | ``` 1025 | 1026 | #### Intermediate 1027 | 97. **Write a function to handle database transactions.** 1028 | Uses MongoDB sessions. 1029 | ```javascript 1030 | const { MongoClient } = require("mongodb"); 1031 | async function transaction() { 1032 | const client = new MongoClient("mongodb://localhost:27017"); 1033 | await client.connect(); 1034 | const session = client.startSession(); 1035 | try { 1036 | await session.withTransaction(async () => { 1037 | const db = client.db("test"); 1038 | await db.collection("users").insertOne({ name: "John" }, { session }); 1039 | }); 1040 | console.log("Transaction complete"); 1041 | } finally { 1042 | await session.endSession(); 1043 | await client.close(); 1044 | } 1045 | } 1046 | transaction(); 1047 | ``` 1048 | 1049 | 98. **How do you use an ORM in Node.js?** 1050 | Uses Mongoose (mock). 1051 | ```javascript 1052 | const mongoose = require("mongoose"); 1053 | mongoose.connect("mongodb://localhost:27017/test"); 1054 | const User = mongoose.model("User", new mongoose.Schema({ name: String })); 1055 | async function saveUser() { 1056 | await new User({ name: "John" }).save(); 1057 | console.log("Saved"); 1058 | } 1059 | saveUser(); 1060 | ``` 1061 | 1062 | 99. **Write a function to paginate database results.** 1063 | Limits and skips records. 1064 | ```javascript 1065 | const { MongoClient } = require("mongodb"); 1066 | async function paginate(page, limit) { 1067 | const client = new MongoClient("mongodb://localhost:27017"); 1068 | await client.connect(); 1069 | const db = client.db("test"); 1070 | const data = await db.collection("users") 1071 | .find() 1072 | .skip((page - 1) * limit) 1073 | .limit(limit) 1074 | .toArray(); 1075 | console.log(data); 1076 | await client.close(); 1077 | } 1078 | paginate(1, 10); 1079 | ``` 1080 | 1081 | 100. **How do you index database collections?** 1082 | Creates indexes for performance. 1083 | ```javascript 1084 | const { MongoClient } = require("mongodb"); 1085 | async function createIndex() { 1086 | const client = new MongoClient("mongodb://localhost:27017"); 1087 | await client.connect(); 1088 | const db = client.db("test"); 1089 | await db.collection("users").createIndex({ name: 1 }); 1090 | console.log("Index created"); 1091 | await client.close(); 1092 | } 1093 | createIndex(); 1094 | ``` 1095 | 1096 | 101. **Write a function to aggregate database data.** 1097 | Uses MongoDB aggregation. 1098 | ```javascript 1099 | const { MongoClient } = require("mongodb"); 1100 | async function aggregate() { 1101 | const client = new MongoClient("mongodb://localhost:27017"); 1102 | await client.connect(); 1103 | const db = client.db("test"); 1104 | const data = await db.collection("users").aggregate([ 1105 | { $group: { _id: "$age", count: { $sum: 1 } } } 1106 | ]).toArray(); 1107 | console.log(data); 1108 | await client.close(); 1109 | } 1110 | aggregate(); 1111 | ``` 1112 | 1113 | 102. **How do you handle database connection pooling?** 1114 | Reuses connections. 1115 | ```javascript 1116 | const { MongoClient } = require("mongodb"); 1117 | const client = new MongoClient("mongodb://localhost:27017", { maxPoolSize: 10 }); 1118 | async function query() { 1119 | await client.connect(); 1120 | const db = client.db("test"); 1121 | console.log(await db.collection("users").findOne()); 1122 | await client.close(); 1123 | } 1124 | query(); 1125 | ``` 1126 | 1127 | #### Advanced 1128 | 103. **Write a function to optimize database queries.** 1129 | Uses selective fields. 1130 | ```javascript 1131 | const { MongoClient } = require("mongodb"); 1132 | async function optimizeQuery() { 1133 | const client = new MongoClient("mongodb://localhost:27017"); 1134 | await client.connect(); 1135 | const db = client.db("test"); 1136 | const data = await db.collection("users").findOne( 1137 | { name: "John" }, 1138 | { projection: { name: 1 } } 1139 | ); 1140 | console.log(data); 1141 | await client.close(); 1142 | } 1143 | optimizeQuery(); 1144 | ``` 1145 | 1146 | 104. **How do you implement database migrations?** 1147 | Uses migration scripts. 1148 | ```javascript 1149 | const { MongoClient } = require("mongodb"); 1150 | async function migrate() { 1151 | const client = new MongoClient("mongodb://localhost:27017"); 1152 | await client.connect(); 1153 | const db = client.db("test"); 1154 | await db.collection("users").updateMany({}, { $set: { status: "active" } }); 1155 | console.log("Migrated"); 1156 | await client.close(); 1157 | } 1158 | migrate(); 1159 | ``` 1160 | 1161 | 105. **Write a function to monitor database performance.** 1162 | Logs query time. 1163 | ```javascript 1164 | const { MongoClient } = require("mongodb"); 1165 | async function monitorDB() { 1166 | const client = new MongoClient("mongodb://localhost:27017"); 1167 | await client.connect(); 1168 | const db = client.db("test"); 1169 | const start = performance.now(); 1170 | await db.collection("users").find().toArray(); 1171 | console.log(`Query time: ${performance.now() - start}ms`); 1172 | await client.close(); 1173 | } 1174 | monitorDB(); 1175 | ``` 1176 | 1177 | 106. **How do you secure database connections?** 1178 | Uses SSL and authentication. 1179 | ```javascript 1180 | const { MongoClient } = require("mongodb"); 1181 | const client = new MongoClient("mongodb://localhost:27017", { 1182 | ssl: true, 1183 | auth: { username: "user", password: "pass" } 1184 | }); 1185 | async function secureConnect() { 1186 | await client.connect(); 1187 | console.log("Secure connection"); 1188 | await client.close(); 1189 | } 1190 | secureConnect(); 1191 | ``` 1192 | 1193 | 107. **Write a function to cache database results.** 1194 | Uses in-memory cache. 1195 | ```javascript 1196 | const { MongoClient } = require("mongodb"); 1197 | const cache = new Map(); 1198 | async function cachedQuery(key) { 1199 | if (cache.has(key)) return cache.get(key); 1200 | const client = new MongoClient("mongodb://localhost:27017"); 1201 | await client.connect(); 1202 | const db = client.db("test"); 1203 | const data = await db.collection("users").findOne({ name: key }); 1204 | cache.set(key, data); 1205 | await client.close(); 1206 | return data; 1207 | } 1208 | cachedQuery("John").then(console.log); 1209 | ``` 1210 | 1211 | 108. **How do you handle large-scale database operations?** 1212 | Uses batch processing. 1213 | ```javascript 1214 | const { MongoClient } = require("mongodb"); 1215 | async function batchProcess() { 1216 | const client = new MongoClient("mongodb://localhost:27017"); 1217 | await client.connect(); 1218 | const db = client.db("test"); 1219 | const bulk = db.collection("users").initializeUnorderedBulkOp(); 1220 | bulk.insert({ name: "John" }); 1221 | bulk.insert({ name: "Jane" }); 1222 | await bulk.execute(); 1223 | console.log("Batch processed"); 1224 | await client.close(); 1225 | } 1226 | batchProcess(); 1227 | ``` 1228 | 1229 | ## Performance Optimization 1230 | 1231 | ### Basic 1232 | 109. **What is performance optimization in Node.js?** 1233 | Improves speed and resource usage. 1234 | ```javascript 1235 | console.log("Optimized Node.js"); 1236 | ``` 1237 | 1238 | 110. **How do you profile Node.js applications?** 1239 | Uses `--prof` flag (mock). 1240 | ```javascript 1241 | function heavyTask() { 1242 | for (let i = 0; i < 1e6; i++) Math.sqrt(i); 1243 | } 1244 | heavyTask(); 1245 | ``` 1246 | 1247 | 111. **How do you optimize CPU-bound tasks?** 1248 | Offloads to workers. 1249 | ```javascript 1250 | const { Worker, isMainThread } = require("worker_threads"); 1251 | if (isMainThread) { 1252 | new Worker(__filename); 1253 | } else { 1254 | for (let i = 0; i < 1e6; i++) Math.sqrt(i); 1255 | console.log("Done"); 1256 | } 1257 | ``` 1258 | 1259 | 112. **How do you reduce memory usage?** 1260 | Avoids large objects. 1261 | ```javascript 1262 | function optimizeMemory() { 1263 | const smallArray = new Array(100).fill(0); 1264 | console.log("Small array created"); 1265 | } 1266 | optimizeMemory(); 1267 | ``` 1268 | 1269 | 113. **How do you handle async performance?** 1270 | Uses Promise.all. 1271 | ```javascript 1272 | async function asyncOptimize() { 1273 | await Promise.all([ 1274 | new Promise(r => setTimeout(r, 1000)), 1275 | new Promise(r => setTimeout(r, 1000)) 1276 | ]); 1277 | console.log("Parallel tasks complete"); 1278 | } 1279 | asyncOptimize(); 1280 | ``` 1281 | 1282 | 114. **How do you visualize performance metrics?** 1283 | Plots CPU usage. 1284 | ```python 1285 | import matplotlib.pyplot as plt 1286 | def plot_cpu_usage(usage): 1287 | plt.plot(usage, 'o-', label='CPU Usage (%)') 1288 | plt.title('Node.js CPU Performance') 1289 | plt.savefig('cpu_usage.png') 1290 | ``` 1291 | 1292 | #### Intermediate 1293 | 115. **Write a function to optimize HTTP request handling.** 1294 | Reuses connections. 1295 | ```javascript 1296 | const http = require("http"); 1297 | const agent = new http.Agent({ keepAlive: true }); 1298 | http.createServer((req, res) => res.end("Optimized")).listen(3000, { agent }); 1299 | ``` 1300 | 1301 | 116. **How do you use caching for performance?** 1302 | Stores frequent results. 1303 | ```javascript 1304 | const cache = new Map(); 1305 | function cachedFn(key, fn) { 1306 | if (cache.has(key)) return cache.get(key); 1307 | const result = fn(); 1308 | cache.set(key, result); 1309 | return result; 1310 | } 1311 | console.log(cachedFn("test", () => "Result")); 1312 | ``` 1313 | 1314 | 117. **Write a function to batch database operations.** 1315 | Reduces query overhead. 1316 | ```javascript 1317 | const { MongoClient } = require("mongodb"); 1318 | async function batchOps() { 1319 | const client = new MongoClient("mongodb://localhost:27017"); 1320 | await client.connect(); 1321 | const db = client.db("test"); 1322 | await db.collection("users").insertMany([{ name: "A" }, { name: "B" }]); 1323 | console.log("Batch complete"); 1324 | await client.close(); 1325 | } 1326 | batchOps(); 1327 | ``` 1328 | 1329 | 118. **How do you optimize file streaming?** 1330 | Uses efficient streams. 1331 | ```javascript 1332 | const fs = require("fs"); 1333 | fs.createReadStream("large.txt") 1334 | .pipe(fs.createWriteStream("copy.txt")) 1335 | .on("finish", () => console.log("Streamed")); 1336 | ``` 1337 | 1338 | 119. **Write a function to monitor memory leaks.** 1339 | Tracks memory usage. 1340 | ```javascript 1341 | function monitorLeaks() { 1342 | setInterval(() => { 1343 | console.log(`Heap: ${process.memoryUsage().heapUsed / 1024 / 1024} MB`); 1344 | }, 1000); 1345 | } 1346 | monitorLeaks(); 1347 | ``` 1348 | 1349 | 120. **How do you scale Node.js applications?** 1350 | Uses clustering. 1351 | ```javascript 1352 | const cluster = require("cluster"); 1353 | const http = require("http"); 1354 | if (cluster.isMaster) { 1355 | cluster.fork(); 1356 | } else { 1357 | http.createServer((req, res) => res.end("Scaled")).listen(3000); 1358 | } 1359 | ``` 1360 | 1361 | #### Advanced 1362 | 121. **Write a function to profile async performance.** 1363 | Measures async task time. 1364 | ```javascript 1365 | async function profileAsync() { 1366 | const start = performance.now(); 1367 | await new Promise(r => setTimeout(r, 1000)); 1368 | console.log(`Async time: ${performance.now() - start}ms`); 1369 | } 1370 | profileAsync(); 1371 | ``` 1372 | 1373 | 122. **How do you implement load balancing?** 1374 | Distributes requests. 1375 | ```javascript 1376 | const cluster = require("cluster"); 1377 | const http = require("http"); 1378 | const numCPUs = 2; 1379 | if (cluster.isMaster) { 1380 | for (let i = 0; i < numCPUs; i++) cluster.fork(); 1381 | } else { 1382 | http.createServer((req, res) => res.end("Balanced")).listen(3000); 1383 | } 1384 | ``` 1385 | 1386 | 123. **Write a function to optimize database indexing.** 1387 | Creates efficient indexes. 1388 | ```javascript 1389 | const { MongoClient } = require("mongodb"); 1390 | async function optimizeIndex() { 1391 | const client = new MongoClient("mongodb://localhost:27017"); 1392 | await client.connect(); 1393 | const db = client.db("test"); 1394 | await db.collection("users").createIndex({ name: 1, age: 1 }); 1395 | console.log("Compound index created"); 1396 | await client.close(); 1397 | } 1398 | optimizeIndex(); 1399 | ``` 1400 | 1401 | 124. **How do you use Redis for caching?** 1402 | Stores data in memory. 1403 | ```javascript 1404 | const redis = require("redis"); 1405 | const client = redis.createClient(); 1406 | async function cacheData(key, value) { 1407 | await client.connect(); 1408 | await client.set(key, value); 1409 | console.log(await client.get(key)); 1410 | await client.disconnect(); 1411 | } 1412 | cacheData("test", "Cached"); 1413 | ``` 1414 | 1415 | 125. **Write a function to audit performance bottlenecks.** 1416 | Logs slow operations. 1417 | ```javascript 1418 | function auditBottleneck(fn) { 1419 | const start = performance.now(); 1420 | fn(); 1421 | const time = performance.now() - start; 1422 | if (time > 100) console.log(`Slow operation: ${time}ms`); 1423 | } 1424 | auditBottleneck(() => Array(1e6).fill(0).map(Math.sqrt)); 1425 | ``` 1426 | 1427 | 126. **How do you optimize Node.js for AI workloads?** 1428 | Offloads ML tasks. 1429 | ```javascript 1430 | const { Worker } = require("worker_threads"); 1431 | if (require("worker_threads").isMainThread) { 1432 | new Worker(__filename); 1433 | } else { 1434 | // Mock ML computation 1435 | console.log("ML task complete"); 1436 | } 1437 | ``` 1438 | 1439 | ## Testing 1440 | 1441 | ### Basic 1442 | 127. **What is testing in Node.js?** 1443 | Verifies code functionality. 1444 | ```javascript 1445 | function add(a, b) { 1446 | return a + b; 1447 | } 1448 | console.log(add(2, 3) === 5 ? "Pass" : "Fail"); 1449 | ``` 1450 | 1451 | 128. **How do you write unit tests in Node.js?** 1452 | Uses Jest (mock). 1453 | ```javascript 1454 | function sum(a, b) { 1455 | return a + b; 1456 | } 1457 | const test = sum(2, 3) === 5 ? "Pass" : "Fail"; 1458 | console.log(test); 1459 | ``` 1460 | 1461 | 129. **How do you use assertions in Node.js?** 1462 | Uses `assert`. 1463 | ```javascript 1464 | const assert = require("assert"); 1465 | assert.strictEqual(2 + 3, 5, "Sum failed"); 1466 | console.log("Test passed"); 1467 | ``` 1468 | 1469 | 130. **How do you test asynchronous functions?** 1470 | Handles promises. 1471 | ```javascript 1472 | async function asyncFn() { 1473 | return "Done"; 1474 | } 1475 | asyncFn().then(result => console.log(result === "Done" ? "Pass" : "Fail")); 1476 | ``` 1477 | 1478 | 131. **How do you mock dependencies in tests?** 1479 | Overrides modules. 1480 | ```javascript 1481 | const mock = { add: () => 5 }; 1482 | console.log(mock.add() === 5 ? "Pass" : "Fail"); 1483 | ``` 1484 | 1485 | 132. **How do you visualize test coverage?** 1486 | Plots coverage metrics. 1487 | ```python 1488 | import matplotlib.pyplot as plt 1489 | def plot_test_coverage(coverage): 1490 | plt.bar(["Functions", "Lines"], coverage, label="Coverage (%)") 1491 | plt.title("Test Coverage") 1492 | plt.savefig("test_coverage.png") 1493 | ``` 1494 | 1495 | #### Intermediate 1496 | 133. **Write a function to test API endpoints.** 1497 | Mocks HTTP requests. 1498 | ```javascript 1499 | const http = require("http"); 1500 | http.createServer((req, res) => res.end("OK")).listen(3000); 1501 | const testApi = () => { 1502 | http.get("http://localhost:3000", res => { 1503 | let data = ""; 1504 | res.on("data", chunk => (data += chunk)); 1505 | res.on("end", () => console.log(data === "OK" ? "Pass" : "Fail")); 1506 | }); 1507 | }; 1508 | testApi(); 1509 | ``` 1510 | 1511 | 134. **How do you test middleware?** 1512 | Simulates requests. 1513 | ```javascript 1514 | const express = require("express"); 1515 | const app = express(); 1516 | app.use((req, res, next) => { 1517 | req.test = "Tested"; 1518 | next(); 1519 | }); 1520 | const mockReq = {}; 1521 | const mockRes = {}; 1522 | const mockNext = () => console.log(mockReq.test === "Tested" ? "Pass" : "Fail"); 1523 | app._router.handle(mockReq, mockRes, mockNext); 1524 | ``` 1525 | 1526 | 135. **Write a function to test database operations.** 1527 | Verifies queries. 1528 | ```javascript 1529 | const { MongoClient } = require("mongodb"); 1530 | async function testDB() { 1531 | const client = new MongoClient("mongodb://localhost:27017"); 1532 | await client.connect(); 1533 | const db = client.db("test"); 1534 | await db.collection("users").insertOne({ name: "Test" }); 1535 | const data = await db.collection("users").findOne({ name: "Test" }); 1536 | console.log(data ? "Pass" : "Fail"); 1537 | await client.close(); 1538 | } 1539 | testDB(); 1540 | ``` 1541 | 1542 | 136. **How do you use test-driven development (TDD)?** 1543 | Writes tests first. 1544 | ```javascript 1545 | // Test 1546 | const assert = require("assert"); 1547 | assert.strictEqual(multiply(2, 3), 6); 1548 | // Implementation 1549 | function multiply(a, b) { 1550 | return a * b; 1551 | } 1552 | console.log("TDD passed"); 1553 | ``` 1554 | 1555 | 137. **Write a function to mock API responses.** 1556 | Simulates server responses. 1557 | ```javascript 1558 | const mockResponse = () => ({ data: "Mock" }); 1559 | console.log(mockResponse().data === "Mock" ? "Pass" : "Fail"); 1560 | ``` 1561 | 1562 | 138. **How do you test error handling?** 1563 | Simulates errors. 1564 | ```javascript 1565 | function riskyFn() { 1566 | throw new Error("Test error"); 1567 | } 1568 | try { 1569 | riskyFn(); 1570 | console.log("Fail"); 1571 | } catch { 1572 | console.log("Pass"); 1573 | } 1574 | ``` 1575 | 1576 | #### Advanced 1577 | 139. **Write a function to test performance-critical code.** 1578 | Measures execution time. 1579 | ```javascript 1580 | function testPerformance(fn) { 1581 | const start = performance.now(); 1582 | fn(); 1583 | const time = performance.now() - start; 1584 | console.log(time < 100 ? "Pass" : "Fail"); 1585 | } 1586 | testPerformance(() => Array(1e5).fill(0).map(Math.sqrt)); 1587 | ``` 1588 | 1589 | 140. **How do you test WebSocket servers?** 1590 | Simulates client connections. 1591 | ```javascript 1592 | const WebSocket = require("ws"); 1593 | const wss = new WebSocket.Server({ port: 3000 }); 1594 | wss.on("connection", ws => ws.send("Test")); 1595 | const ws = new WebSocket("ws://localhost:3000"); 1596 | ws.on("message", msg => console.log(msg.toString() === "Test" ? "Pass" : "Fail")); 1597 | ``` 1598 | 1599 | 141. **Write a function to automate end-to-end tests.** 1600 | Simulates user flows. 1601 | ```javascript 1602 | const http = require("http"); 1603 | http.createServer((req, res) => res.end("E2E")).listen(3000); 1604 | const testE2E = () => { 1605 | http.get("http://localhost:3000", res => { 1606 | let data = ""; 1607 | res.on("data", chunk => (data += chunk)); 1608 | res.on("end", () => console.log(data === "E2E" ? "Pass" : "Fail")); 1609 | }); 1610 | }; 1611 | testE2E(); 1612 | ``` 1613 | 1614 | 142. **How do you test database transactions?** 1615 | Verifies atomicity. 1616 | ```javascript 1617 | const { MongoClient } = require("mongodb"); 1618 | async function testTransaction() { 1619 | const client = new MongoClient("mongodb://localhost:27017"); 1620 | await client.connect(); 1621 | const session = client.startSession(); 1622 | try { 1623 | await session.withTransaction(async () => { 1624 | const db = client.db("test"); 1625 | await db.collection("users").insertOne({ name: "Test" }, { session }); 1626 | }); 1627 | console.log("Pass"); 1628 | } catch { 1629 | console.log("Fail"); 1630 | } finally { 1631 | await session.endSession(); 1632 | await client.close(); 1633 | } 1634 | } 1635 | testTransaction(); 1636 | ``` 1637 | 1638 | 143. **Write a function to monitor test performance.** 1639 | Logs test times. 1640 | ```javascript 1641 | function monitorTest(fn) { 1642 | const start = performance.now(); 1643 | fn(); 1644 | console.log(`Test time: ${performance.now() - start}ms`); 1645 | } 1646 | monitorTest(() => console.log("Test")); 1647 | ``` 1648 | 1649 | 144. **How do you implement continuous integration for tests?** 1650 | Mocks CI pipeline. 1651 | ```javascript 1652 | function runCI() { 1653 | const tests = [() => true, () => true]; 1654 | const results = tests.map(test => test()); 1655 | console.log(results.every(r => r) ? "CI Pass" : "CI Fail"); 1656 | } 1657 | runCI(); 1658 | ``` 1659 | 1660 | ## Integration with AI/ML 1661 | 1662 | ### Basic 1663 | 145. **How do you integrate Node.js with AI/ML models?** 1664 | Serves model predictions. 1665 | ```javascript 1666 | const express = require("express"); 1667 | const app = express(); 1668 | app.get("/predict", (req, res) => res.json({ prediction: "Positive" })); 1669 | app.listen(3000); 1670 | ``` 1671 | 1672 | 146. **How do you create an API for ML predictions?** 1673 | Handles prediction requests. 1674 | ```javascript 1675 | const express = require("express"); 1676 | const app = express(); 1677 | app.use(express.json()); 1678 | app.post("/predict", (req, res) => res.json({ result: req.body.data })); 1679 | app.listen(3000); 1680 | ``` 1681 | 1682 | 147. **How do you handle ML model inputs?** 1683 | Validates input data. 1684 | ```javascript 1685 | const express = require("express"); 1686 | const app = express(); 1687 | app.use(express.json()); 1688 | app.post("/predict", (req, res) => { 1689 | if (Array.isArray(req.body.data)) res.json({ valid: true }); 1690 | else res.status(400).json({ error: "Invalid input" }); 1691 | }); 1692 | app.listen(3000); 1693 | ``` 1694 | 1695 | 148. **How do you serve ML model outputs?** 1696 | Returns predictions. 1697 | ```javascript 1698 | const express = require("express"); 1699 | const app = express(); 1700 | app.get("/results", (req, res) => res.json({ output: Math.random() })); 1701 | app.listen(3000); 1702 | ``` 1703 | 1704 | 149. **How do you log ML model performance?** 1705 | Tracks prediction time. 1706 | ```javascript 1707 | const express = require("express"); 1708 | const app = express(); 1709 | app.get("/predict", (req, res) => { 1710 | const start = performance.now(); 1711 | res.json({ prediction: "Done" }); 1712 | console.log(`Prediction time: ${performance.now() - start}ms`); 1713 | }); 1714 | app.listen(3000); 1715 | ``` 1716 | 1717 | 150. **How do you visualize ML model metrics?** 1718 | Plots accuracy. 1719 | ```python 1720 | import matplotlib.pyplot as plt 1721 | def plot_model_metrics(accuracy): 1722 | plt.plot(accuracy, 'o-', label='Accuracy') 1723 | plt.title('ML Model Performance') 1724 | plt.savefig('model_metrics.png') 1725 | ``` 1726 | 1727 | #### Intermediate 1728 | 151. **Write a function to integrate TensorFlow.js in Node.js.** 1729 | Runs ML models (mock). 1730 | ```javascript 1731 | const express = require("express"); 1732 | const app = express(); 1733 | app.get("/predict", (req, res) => { 1734 | // Mock TensorFlow.js 1735 | res.json({ prediction: Math.random() }); 1736 | }); 1737 | app.listen(3000); 1738 | ``` 1739 | 1740 | 152. **How do you handle large ML datasets in Node.js?** 1741 | Streams data. 1742 | ```javascript 1743 | const fs = require("fs"); 1744 | const stream = fs.createReadStream("dataset.csv"); 1745 | stream.on("data", chunk => console.log("Processing:", chunk.toString())); 1746 | ``` 1747 | 1748 | 153. **Write a function to cache ML predictions.** 1749 | Stores results in Redis. 1750 | ```javascript 1751 | const redis = require("redis"); 1752 | const client = redis.createClient(); 1753 | async function cachePrediction(key, value) { 1754 | await client.connect(); 1755 | await client.set(key, JSON.stringify(value)); 1756 | console.log(await client.get(key)); 1757 | await client.disconnect(); 1758 | } 1759 | cachePrediction("pred1", { result: 0.9 }); 1760 | ``` 1761 | 1762 | 154. **How do you implement real-time ML predictions?** 1763 | Uses WebSockets. 1764 | ```javascript 1765 | const WebSocket = require("ws"); 1766 | const wss = new WebSocket.Server({ port: 3000 }); 1767 | wss.on("connection", ws => { 1768 | setInterval(() => ws.send(JSON.stringify({ prediction: Math.random() })), 1000); 1769 | }); 1770 | ``` 1771 | 1772 | 155. **Write a function to validate ML model inputs.** 1773 | Checks data format. 1774 | ```javascript 1775 | const express = require("express"); 1776 | const app = express(); 1777 | app.use(express.json()); 1778 | app.post("/predict", (req, res) => { 1779 | const { data } = req.body; 1780 | if (data && typeof data === "object") res.json({ valid: true }); 1781 | else res.status(400).json({ error: "Invalid" }); 1782 | }); 1783 | app.listen(3000); 1784 | ``` 1785 | 1786 | 156. **How do you optimize ML API performance?** 1787 | Uses async processing. 1788 | ```javascript 1789 | const express = require("express"); 1790 | const app = express(); 1791 | app.get("/predict", async (req, res) => { 1792 | const result = await new Promise(r => setTimeout(() => r(Math.random()), 100)); 1793 | res.json({ prediction: result }); 1794 | }); 1795 | app.listen(3000); 1796 | ``` 1797 | 1798 | #### Advanced 1799 | 157. **Write a function to integrate ONNX models in Node.js.** 1800 | Runs ONNX models (mock). 1801 | ```javascript 1802 | const express = require("express"); 1803 | const app = express(); 1804 | app.get("/onnx", (req, res) => { 1805 | // Mock ONNX inference 1806 | res.json({ output: Math.random() }); 1807 | }); 1808 | app.listen(3000); 1809 | ``` 1810 | 1811 | 158. **How do you handle streaming ML predictions?** 1812 | Streams results. 1813 | ```javascript 1814 | const express = require("express"); 1815 | const app = express(); 1816 | app.get("/stream", (req, res) => { 1817 | res.write("data: " + Math.random() + "\n\n"); 1818 | setTimeout(() => res.end(), 1000); 1819 | }); 1820 | app.listen(3000); 1821 | ``` 1822 | 1823 | 159. **Write a function to monitor ML model performance.** 1824 | Logs inference time. 1825 | ```javascript 1826 | const express = require("express"); 1827 | const app = express(); 1828 | app.get("/predict", (req, res) => { 1829 | const start = performance.now(); 1830 | res.json({ prediction: Math.random() }); 1831 | console.log(`Inference time: ${performance.now() - start}ms`); 1832 | }); 1833 | app.listen(3000); 1834 | ``` 1835 | 1836 | 160. **How do you secure ML model APIs?** 1837 | Uses JWT authentication. 1838 | ```javascript 1839 | const express = require("express"); 1840 | const app = express(); 1841 | app.use((req, res, next) => { 1842 | if (req.headers.authorization === "Bearer token") next(); 1843 | else res.status(401).json({ error: "Unauthorized" }); 1844 | }); 1845 | app.get("/predict", (req, res) => res.json({ prediction: "Secure" })); 1846 | app.listen(3000); 1847 | ``` 1848 | 1849 | 161. **Write a function to handle model versioning.** 1850 | Switches model versions. 1851 | ```javascript 1852 | const express = require("express"); 1853 | const app = express(); 1854 | app.get("/predict/:version", (req, res) => { 1855 | res.json({ version: req.params.version, prediction: Math.random() }); 1856 | }); 1857 | app.listen(3000); 1858 | ``` 1859 | 1860 | 162. **How do you deploy Node.js ML apps?** 1861 | Mocks deployment. 1862 | ```javascript 1863 | const express = require("express"); 1864 | const app = express(); 1865 | app.get("/status", (req, res) => res.json({ status: "Deployed" })); 1866 | app.listen(3000, () => console.log("Deployed")); 1867 | ``` 1868 | 1869 | 163. **Write a function to visualize ML predictions.** 1870 | Generates prediction charts. 1871 | ```javascript 1872 | const fs = require("fs"); 1873 | const predictions = [0.1, 0.5, 0.9]; 1874 | fs.writeFileSync("predictions.json", JSON.stringify(predictions)); 1875 | console.log("Predictions saved"); 1876 | ``` 1877 | 1878 | 164. **How do you handle model errors in Node.js?** 1879 | Catches inference errors. 1880 | ```javascript 1881 | const express = require("express"); 1882 | const app = express(); 1883 | app.get("/predict", (req, res) => { 1884 | try { 1885 | throw new Error("Model error"); 1886 | } catch (err) { 1887 | res.status(500).json({ error: err.message }); 1888 | } 1889 | }); 1890 | app.listen(3000); 1891 | ``` 1892 | 1893 | 165. **Write a function to audit ML model APIs.** 1894 | Logs API usage. 1895 | ```javascript 1896 | const express = require("express"); 1897 | const app = express(); 1898 | app.use((req, res, next) => { 1899 | console.log(`API call: ${req.method} ${req.url}`); 1900 | next(); 1901 | }); 1902 | app.get("/predict", (req, res) => res.json({ prediction: "Audited" })); 1903 | app.listen(3000); 1904 | ``` 1905 | 1906 | 166. **How do you optimize ML model inference?** 1907 | Uses workers. 1908 | ```javascript 1909 | const { Worker } = require("worker_threads"); 1910 | if (require("worker_threads").isMainThread) { 1911 | new Worker(__filename); 1912 | } else { 1913 | console.log("Inference complete"); 1914 | } 1915 | ``` 1916 | 1917 | 167. **Write a function to manage ML model inputs.** 1918 | Validates and processes inputs. 1919 | ```javascript 1920 | const express = require("express"); 1921 | const app = express(); 1922 | app.use(express.json()); 1923 | app.post("/predict", (req, res) => { 1924 | const { data } = req.body; 1925 | if (Array.isArray(data)) res.json({ processed: data.length }); 1926 | else res.status(400).json({ error: "Invalid input" }); 1927 | }); 1928 | app.listen(3000); 1929 | ``` 1930 | 1931 | 168. **How do you implement interactive ML APIs?** 1932 | Handles dynamic inputs. 1933 | ```javascript 1934 | const express = require("express"); 1935 | const app = express(); 1936 | app.use(express.json()); 1937 | app.post("/interactive", (req, res) => { 1938 | res.json({ output: req.body.input || "No input" }); 1939 | }); 1940 | app.listen(3000); 1941 | ``` 1942 | 1943 | 169. **Write a function to visualize model training progress.** 1944 | Logs training metrics. 1945 | ```javascript 1946 | const fs = require("fs"); 1947 | const metrics = { epoch: 1, accuracy: 0.95 }; 1948 | fs.writeFileSync("training.json", JSON.stringify(metrics)); 1949 | console.log("Training logged"); 1950 | ``` 1951 | 1952 | 170. **How do you scale ML APIs in Node.js?** 1953 | Uses clustering and load balancing. 1954 | ```javascript 1955 | const cluster = require("cluster"); 1956 | const express = require("express"); 1957 | if (cluster.isMaster) { 1958 | cluster.fork(); 1959 | } else { 1960 | const app = express(); 1961 | app.get("/predict", (req, res) => res.json({ prediction: "Scaled" })); 1962 | app.listen(3000); 1963 | } 1964 | ``` --------------------------------------------------------------------------------