├── 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 |<%= 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: Bearer56 | 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 |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 |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 |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 |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 |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 |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 |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 |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 |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 |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 |Happy Learning and Good Luck with Your Interviews! ✨
162 |