Modules in Node.js 1.Usage Node.js වල වැඩ කරනකොට Modules කියන concept එක හොඳට තේරුම් ගන්න එක වැදගත්. Modules use කරලා අපිට code එක organized කරන්න, reusable කරන්න, සහ maintainable structure එකක් හදාගන්න පුළුවන්. Module එකක් කියන්නේ functions, variables, objects වගේ code තියෙන file එකක්. ඒවා export කරලා වෙන file වල reuse කරන්න පුළුවන්. 2.Types of Modules in Node.js i. Core Modules (Built-in Modules) මේ modules Node.js එක්කම default එනවා. Install කරන්න ඕන නැහැ. Examples: fs – File System handling http – Create web servers path – Work with file paths os – Operating system details const http = require('http'); http.createServer((req, res) => { res.write("Hello World"); res.end(); }).listen(3000); ii. Local Modules (User-defined Modules) මේවා අපි project එක ඇතුළේ create කරන custom modules. Example: math.js function add(a, b) { return a + b; } module.exports = add; app.js const add = require('./math'); console.log(add(5, 3)); iii. Third-party Modules(External Modules) මේවා වෙන developers ලා හදපු modules. npm (Node Package Manager). හරහා install කරගන්න පුළුවන්. Examples: express mongoose first Install express npm install express const express = require('express'); const app = express(); app.listen(3000); 3.Module Systems in Node.js i. CommonJS Uses require() Uses module.exports Default in Node.js ii. ES Modules (ESM) Uses import and export Modern JavaScript standard Keep learning. Keep building. Let’s grow together as developers. #NodeJS #JavaScriptDeveloper #BackendDeveloper #FullStackDeveloper #SoftwareEngineer #WebDeveloper #TechCareers #CareerGrowth #JobSeekers #DeveloperCommunity #OpenToWork #TechIndustry #CodingSkills #LinkedInLearning
Node.js Modules: Core, Local, Third-party & Systems
More Relevant Posts
-
Node.js — The Runtime That Changed What JavaScript Could Do Before Node.js, JavaScript lived exclusively in the browser. It could animate elements, handle user interactions, and make API calls. But the moment a request left the browser, JavaScript's role ended. The server was someone else's territory — PHP, Python, Ruby, Java. Node.js changed that entirely. Node.js is a JavaScript runtime built on Chrome's V8 engine. It takes JavaScript out of the browser and lets it run anywhere — on servers, in build tools, in command line interfaces, in desktop applications. For the MERN stack, Node.js is the foundation everything else runs on. Express runs on Node. Your build processes run on Node. Your testing tools run on Node. But the architectural decision that makes Node.js interesting is not just that it runs JavaScript. It is how it handles concurrency. Traditional server runtimes handle multiple simultaneous requests by spawning multiple threads. Each request gets its own thread. This works but threads are expensive. Memory usage grows with traffic. Context switching between threads adds overhead. Node.js uses a single-threaded event loop with non-blocking I/O. When Node receives a request that involves waiting — a database query, an API call, reading a file — it does not block the thread and wait for the result. It registers a callback and moves on to handle the next request. When the result arrives, the callback executes. This means a single Node process can handle thousands of concurrent connections without the overhead of managing thousands of threads. Where this model excels: -> APIs that make many database queries and external service calls -> Real-time applications like chat, live notifications, and collaborative tools -> Applications with high concurrency and I/O-heavy workloads -> Microservices that need to be fast and lightweight Where this model requires care: -> CPU-intensive operations like image processing, video encoding, or complex calculations will block the event loop. These should be offloaded to worker threads or separate services. For most MERN applications — web APIs, real-time features, data-driven dashboards — Node's event-driven model is not a limitation. It is a genuine advantage. The npm ecosystem that comes with Node is the largest package registry in the world. Whatever problem you are solving, there is almost certainly a well-maintained package that has already solved it. Has Node.js replaced a traditional backend language in your stack? What drove that decision? #NodeJS #JavaScript #MERN #BackendDevelopment #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Node.js Isn’t Single-Threaded (And Most Developers Still Get This Wrong) When I started learning Node.js, I kept hearing: “Node.js is single-threaded.” That statement is true… but also misleading. After working more deeply with backend systems, I realized something important: 👉 Node.js is single-threaded for JavaScript execution — but not for handling work. Let’s break this down. 1. The JavaScript Thread (Yes, Single-Threaded) Node.js runs JavaScript on a single main thread using the V8 engine. That means: One call stack One task executed at a time No parallel JS execution (unless you use Worker Threads) But then… How does Node handle thousands of requests simultaneously? 2. The Secret: Event Loop + libuv Node.js uses: Event Loop libuv (C++ library) OS-level async capabilities Thread pool (4 threads by default) This is where the magic happens. Example: const fs = require("fs"); console.log("Start"); fs.readFile("file.txt", "utf8", (err, data) => { console.log("File read complete"); }); console.log("End"); Output: Start End File read complete Why? Because fs.readFile() is delegated to libuv, not executed on the main thread. 3. How the Event Loop Actually Works The Event Loop has phases: Timers (setTimeout, setInterval) Pending callbacks Idle/prepare Poll Check (setImmediate) Close callbacks And then there’s: process.nextTick() queue Microtask queue (Promises) Important: 👉 process.nextTick() runs before every phase 👉 Promise microtasks run after each phase This is why understanding event loop order is critical for backend interviews. 4. The Real Danger: Blocking the Event Loop If you do this: while(true) {} You freeze everything. Why? Because the main thread is blocked. No callbacks. No I/O. No requests processed. This is why Node is excellent for: ✅ I/O-heavy apps ❌ CPU-heavy tasks For CPU-intensive work, use: Worker Threads Child Processes Or move heavy work to another service 5. Why Node.js Scales So Well Node doesn’t create a thread per request (like traditional servers). Instead: One event loop Non-blocking I/O Handles thousands of concurrent connections This makes it perfect for: APIs Real-time apps Streaming services Chat systems Final Conclusion Node.js is not “single-threaded” in the way people think. It is: Single-threaded for JavaScript execution Multi-threaded under the hood for I/O handling And that architectural design is what makes it powerful. If you're preparing for backend interviews, truly understanding the event loop is a game-changer. If this helped you, feel free to connect. Let’s grow together #NodeJS #Backend #JavaScript #BackendDev #LearningNodeJS
To view or add a comment, sign in
-
𝗗𝗲𝗺𝘆𝘀𝘁𝗶𝗳𝘆𝗶𝗻𝗴 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁'𝘀 𝗛𝗲𝗮𝗿𝘁𝗯𝗲𝗮𝘁: 𝗧𝗵𝗲 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱 (𝗳𝗼𝗿 𝗠𝗘𝗥𝗡 𝗦𝘁𝗮𝗰𝗸 𝗗𝗲𝘃𝘀!) As MERN stack developers, we constantly work with asynchronous operations – fetching data, handling user input, or setting timers. But how does JavaScript, a single-threaded language, manage all this without freezing the browser? The answer lies in the 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽! Understanding the Event Loop was a "lightbulb moment" for me during my journey into Node.js and React. It truly reveals the magic behind non-blocking operations. 𝗛𝗲𝗿𝗲'𝘀 𝗮 𝘀𝗶𝗺𝗽𝗹𝗶𝗳𝗶𝗲𝗱 𝗯𝗿𝗲𝗮𝗸𝗱𝗼𝘄𝗻 𝗼𝗳 𝘁𝗵𝗲 𝗰𝗼𝗿𝗲 𝗰𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀: 1. 𝗧𝗵𝗲 𝗖𝗮𝗹𝗹 𝗦𝘁𝗮𝗰𝗸: This is where our JavaScript code is executed, one function at a time. It's synchronous and follows a Last-In, First-Out (LIFO) order. 2. 𝗪𝗲𝗯 𝗔𝗣𝗜𝘀 (𝗕𝗿𝗼𝘄𝘀𝗲𝗿) / 𝗖++ 𝗔𝗣𝗜𝘀 (𝗡𝗼𝗱𝗲.𝗷𝘀): When we encounter asynchronous operations like setTimeout(), fetch(), or DOM events, they are offloaded to these specialized environments. They run in the background. 3. 𝗧𝗵𝗲 𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸 𝗤𝘂𝗲𝘂𝗲 (𝗼𝗿 𝗧𝗮𝘀𝗸 𝗤𝘂𝗲𝘂𝗲): Once an asynchronous operation completes (e.g., data is fetched, timer expires), its callback function is moved here, waiting to be executed. 4. 𝗧𝗵𝗲 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽: This is the hero! It constantly checks two things: • Is the Call Stack empty? • Is there anything in the Callback Queue? If the Call Stack is empty, the Event Loop takes the first callback from the Callback Queue and pushes it onto the Call Stack for execution. 𝗪𝗵𝘆 𝗶𝘀 𝘁𝗵𝗶𝘀 𝗶𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗳𝗼𝗿 𝗮 𝗠𝗘𝗥𝗡 𝘀𝘁𝗮𝗰𝗸 𝗱𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿? • 𝗡𝗼𝗻-𝗕𝗹𝗼𝗰𝗸𝗶𝗻𝗴 𝗨𝗜: In React, understanding setState and asynchronous data fetches means you can write UIs that remain responsive. • 𝗘𝗳𝗳𝗶𝗰𝗶𝗲𝗻𝘁 𝗕𝗮𝗰𝗸𝗲𝗻𝗱 (𝗡𝗼𝗱𝗲.𝗷𝘀): For Express servers, knowing how Node handles I/O operations (like database queries with MongoDB) helps you write performant and scalable APIs that don't block other incoming requests. • 𝗗𝗲𝗯𝘂𝗴𝗴𝗶𝗻𝗴 𝗔𝘀𝘆𝗻𝗰 𝗖𝗼𝗱𝗲: When promises aren't resolving as expected, or timers are off, a solid grasp of the Event Loop helps pinpoint issues much faster. This concept truly underpins how modern web applications deliver a smooth user experience. Continuously learning these fundamentals is key to becoming a strong full-stack developer. #JavaScript #EventLoop #MERNStack #WebDevelopment #NodeJS #ReactJS #FrontendDevelopment #BackendDevelopment #InternshipSearch #DeveloperJourney
To view or add a comment, sign in
-
-
🚀 Express.js Revision – Day 1 Today I started revising Express.js, one of the most widely used backend frameworks for Node.js. Instead of jumping directly into complex APIs, I focused on revisiting the core fundamentals of how Express works. 🔹 What is Express? Express is a fast, minimalist, and unopinionated web framework for Node.js that helps us build servers and web applications efficiently. When a user sends a request from the browser: Browser → Server → Express → Response back to the client Express acts as a layer that helps Node.js handle requests and responses easily. 🔹 Library vs Framework (Important Concept) Library A collection of prewritten code. The developer controls when and how to use it. Used for small functionality changes. Framework Provides a structure for the entire application. Control flow is inverted — the framework decides when our code runs. We plug our logic into the framework. Express is a framework, meaning it provides the structure for building web servers. 🔹 Steps to Start an Express Server 1️⃣ Initialize project npm init -y 2️⃣ Install Express npm install express 3️⃣ Import Express in JavaScript const express = require("express"); 4️⃣ Create an Express application const app = express(); 5️⃣ Start the server app.listen(3000, () => { console.log("Server running on port 3000"); }); At this stage, the server starts and waits for incoming requests on localhost:3000. 🔹 Handling Requests in Express Express provides middleware functions such as app.use() which run whenever a request is received. app.use((req, res) => { res.send("Hello World"); }); Here: req (Request Object) → Represents the incoming HTTP request res (Response Object) → Used to send a response back to the client Important thing to understand: HTTP requests arrive in text format, but Express parses them into JavaScript objects (req and res) so developers can easily work with them. 🔹 Sending Responses Express provides the res.send() method to send data back to the browser. It can send: • Strings • Objects • Arrays • Buffers Example: res.send({ color: "red" }); Even though this is a JavaScript object, the browser receives it as JSON. 📌 Key Concepts Revised Today ✔ Express framework fundamentals ✔ Difference between library and framework ✔ Creating an Express server ✔ Understanding req and res objects ✔ Using app.use() middleware ✔ Sending responses using res.send() Consistency is the goal. Starting a daily backend revision series to strengthen fundamentals. #ExpressJS #NodeJS #BackendDevelopment #WebDevelopment #JavaScript #LearningInPublic
To view or add a comment, sign in
-
🚀 From CRUD Developer to Backend Engineer My Laravel Journey When I started with Laravel, my goal was simple: Make CRUD work. Create. Read. Update. Delete. If the data saved correctly, I felt accomplished. But over time, I realized backend engineering is much deeper than CRUD. Here’s how my thinking evolved. 🧱 Stage 1: Basic CRUD Routes. Controllers. Models. Views. I learned how to connect database to UI. It was exciting — but I was just building features, not systems. 🔍 Stage 2: Validation & Relationships Then came: Form Request validation Eloquent relationships Clean query design I stopped thinking in tables and started thinking in data models. Structure began to matter. 🌐 Stage 3: APIs Next was building APIs. That’s when I learned: Response consistency matters API Resources protect structure Versioning saves future pain I realized APIs are contracts — not just JSON outputs. 🏗 Stage 4: Architecture & Security This stage changed everything. I started thinking about: Service layers Modular structure Authentication strategies Rate limiting Token lifecycle Device-aware security Now I wasn’t just building endpoints. I was designing systems. ⚡ Stage 5: Scalability Thinking The biggest shift? Asking different questions: Will this break at scale? What happens if traffic grows 10x? Is this secure in production? Can another developer maintain this easily? Backend engineering is less about writing code — and more about making decisions that survive growth. 💡 Final Reflection CRUD builds confidence. Architecture builds maturity. Scalability builds responsibility. Laravel gave me the tools. Experience taught me how to use them. Where are you in your backend journey? #Laravel #BackendEngineering #SoftwareArchitecture #WebDevelopment #CareerGrowth
To view or add a comment, sign in
-
-
🚀 From CRUD Developer to Backend Engineer My Laravel Journey When I started with Laravel, my goal was simple: Make CRUD work. Create. Read. Update. Delete. If the data saved correctly, I felt accomplished. But over time, I realized backend engineering is much deeper than CRUD. Here’s how my thinking evolved. 🧱 Stage 1: Basic CRUD Routes. Controllers. Models. Views. I learned how to connect database to UI. It was exciting — but I was just building features, not systems. 🔍 Stage 2: Validation & Relationships Then came: Form Request validation Eloquent relationships Clean query design I stopped thinking in tables and started thinking in data models. Structure began to matter. 🌐 Stage 3: APIs Next was building APIs. That’s when I learned: Response consistency matters API Resources protect structure Versioning saves future pain I realized APIs are contracts — not just JSON outputs. 🏗 Stage 4: Architecture & Security This stage changed everything. I started thinking about: Service layers Modular structure Authentication strategies Rate limiting Token lifecycle Device-aware security Now I wasn’t just building endpoints. I was designing systems. ⚡ Stage 5: Scalability Thinking The biggest shift? Asking different questions: Will this break at scale? What happens if traffic grows 10x? Is this secure in production? Can another developer maintain this easily? Backend engineering is less about writing code — and more about making decisions that survive growth. 💡 Final Reflection CRUD builds confidence. Architecture builds maturity. Scalability builds responsibility. Laravel gave me the tools. Experience taught me how to use them. Where are you in your backend journey? #Laravel #BackendEngineering #SoftwareArchitecture #WebDevelopment #CareerGrowth
To view or add a comment, sign in
-
-
Express.js — The Backend Framework That Gets Out of Your Way Node.js gave JavaScript the ability to run on a server. Express.js gave developers the tools to actually build something useful with it. Express is a minimal, unopinionated web framework for Node.js. It handles the fundamental tasks of a backend application without forcing you into a specific architecture or pattern. Here is what Express actually does: -> Routing: maps HTTP methods and URL paths to handler functions -> Middleware: processes requests through a chain of functions before they reach your route handlers -> Request and response handling: gives you clean access to incoming data and full control over what you send back -> Error handling: centralizes error management across your entire application A basic Express server looks like this: const express = require('express'); const app = express(); app.use(express.json()); app.get('/users/:id', async (req, res) => { const user = await User.findById(req.params.id); if (!user) return res.status(404).json({ error: 'User not found' }); res.json(user); }); app.listen(3000); That is a working API endpoint. Receive a request, query MongoDB, return a response. The simplicity is intentional. Middleware is where Express becomes genuinely powerful. Every request passes through a chain of middleware functions before reaching your route handler. Each function can read the request, modify it, respond to it, or pass it to the next function in the chain. This is how authentication works in Express: -> Request arrives at your API -> Authentication middleware verifies the JWT token -> If valid, the middleware attaches the user to the request object and calls next() -> If invalid, it responds with 401 immediately and the route handler never runs -> Your route handler receives a request that is already authenticated Middleware handles authentication, logging, rate limiting, input validation, compression, CORS, and error handling. These concerns are separated from your business logic and applied consistently across every route. The ecosystem around Express is vast. There is a middleware package for almost every problem you will encounter. For the MERN stack, Express serves as the bridge between MongoDB and React. It receives requests from the frontend, queries the database, applies business logic, and returns structured responses. It does this without imposing opinions on how you structure your code. That freedom is both Express's greatest strength and the reason teams need to establish their own conventions early. What conventions does your team follow when structuring an Express application? #ExpressJS #NodeJS #MERN #BackendDevelopment #API #WebDevelopment
To view or add a comment, sign in
-
-
🚀 Day 78 Node.js Fundamentals (Modules, NPM & Packages) Today I learned the core building blocks of Node.js, which are essential before starting serious backend development. 🔹 What is Node.js? • Node.js is a JavaScript runtime environment that allows us to run JavaScript outside the browser, mainly on the server. 🔹 Installing Node.js • After installing Node, we can check if it is working with: node -v npm -v 🔹 Node REPL • REPL stands for Read – Evaluate – Print – Loop. It lets us run JavaScript directly in the terminal. 🔹 Running a Node File • We can create a JavaScript file and run it with Node. app.js console.log("Hello from Node.js"); Run the file: node app.js 🔹 Process in Node • Node provides a process object that gives information about the running program. 🔹 Exporting Modules (File Level) We can export functions from one file and use them in another. math.js function add(a, b) { return a + b; } module.exports = add; app.js const add = require("./math"); console.log(add(2,3)); 🔹 Exporting Modules from a Directory Node automatically reads the index.js file inside a folder. // utils/index.js module.exports = { name: "Utility Module" }; 🔹 NPM (Node Package Manager) NPM allows us to install and manage libraries for our projects. npm init -y 🔹 package.json This file stores important project information such as: • Project name & version • Installed dependencies • Scripts and configurations Example: { "name": "node-project", "version": "1.0.0" } 🔹 Installing Packages • Packages can be installed using NPM: npm install express 🔹 Local vs Global Installation • Local installation (project specific): npm install nodemon • Global installation (available system-wide): npm install -g nodemon 📌 Key Takeaway Today’s learning helped me understand the foundation of Node.js development — REPL, modules, NPM, package management, and running JavaScript on the server. Mastering these basics is the first step toward building scalable backend applications. Continuing my MERN Journey 🚀 #NodeJS #BackendDevelopment #JavaScript #WebDevelopment #LearningInPublic #FullStackJourney
To view or add a comment, sign in
-
Choosing between Ruby on Rails and Node.js isn't just a technical preference — it's an architectural commitment that shapes your team's velocity, scalability ceiling, and long-term maintenance cost. Here's what CTOs and product leads need to weigh before picking a backend stack: • Performance vs. Development Speed — Node.js wins on raw throughput with its non-blocking I/O and single-threaded event loop, but Rails wins on build speed. If you're shipping an MVP in 2 weeks, Rails' convention-over-configuration model gets you running faster. If you're targeting high-concurrency real-time traffic from day one, Node.js is the safer bet. • Threading Model as an Architecture Decision — Rails' multi-threading is powerful but context-switching costs compound in complex apps. Node.js sidesteps this with its event loop — elegant for I/O-heavy workloads, but dangerous if any operation blocks the thread. Know your load profile before you commit. • Package Ecosystems: RubyGems vs. NPM — NPM's scale (backed by GitHub) gives Node.js a massive library advantage. Rails' Gems are curated and battle-tested but narrower. If your team is already fluent in JavaScript across the full stack, NPM consolidates your dependency surface significantly. • ORM and Database Coupling — ActiveRecord in Rails is one of the most productive ORMs in existence for relational database applications. If your domain model is data-heavy and complex, this alone can justify the Rails choice. Node.js requires you to select and configure your own ORM layer. • Scalability Trade-offs — Twitter migrated away from Rails at scale. That story matters. Node.js was architecturally designed for horizontal scaling in distributed environments. If your growth trajectory looks like a startup-to-enterprise path, factor this early. Reflection questions for your team: 1️⃣ Is your bottleneck CPU-bound computation or I/O-bound concurrent requests? The answer determines which threading model fits. 2️⃣ Does your team have full-stack JavaScript fluency, or is the backend squad a separate Ruby-specialized team? 3️⃣ Are you optimizing for time-to-first-feature (Rails) or time-to-first-scale (Node.js)? Read the full guide: https://lnkd.in/dHp8AwkT #Monocubed #WebDevelopment #NodeJS #RubyOnRails #BackendArchitecture #SoftwareEngineering
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development