module.exports vs. exports: Do you know the difference? 🤯 If you've spent any time in Node.js, you've likely typed these words a thousand times. But have you ever accidentally "broken" your export by reassignment? Understanding how Node.js handles exports is the key to writing clean, modular, and bug-free backend code. Here is everything you need to know: 🧱 The "Big Secret" In every Node.js module, exports is simply a shortcut (a reference) pointing to module.exports. Think of it like this: ✅ When to use exports Use it for Named Exports. If you want to export multiple functions or variables, exports is your best friend. exports.add = (a, b) => a + b; exports.subtract = (a, b) => a - b; ⚠️ The "Gotcha" (The Reassignment Trap) This is where most developers trip up. If you try to assign a function directly to exports, you break the reference to module.exports. WRONG: exports = (name) => { ... }; (This just changes the local variable; Node.js still returns the empty module.exports object!) RIGHT: module.exports = (name) => { ... }; (This tells Node.js: "I want this specific function to BE the module.") 💡 Key Takeaways: The Object wins: Node.js always returns module.exports, not exports. Single Export: If you’re exporting a single class or function, use module.exports. Multiple Exports: You can use exports.name = ... for convenience. Mastering this distinction is the first step from being a "copy-paste" developer to a true Node.js engineer. #NodeJS #JavaScript #BackendDevelopment #SoftwareArchitecture #CodingBestPractices #WebDev
Node.js exports vs module.exports: Key differences
More Relevant Posts
-
Most developers use require() in Node.js every day, but very few know what actually happens behind the scenes. While exploring the Node.js source code, I found that require() follows a series of internal steps before a module is available in your application. Here’s a simplified breakdown of how it works: Step 1: Resolving the module Node first determines where the module exists. It checks for local files, JSON files, and modules inside the node_modules directory. Step 2: Loading the module Once the correct file is found, Node reads the file content depending on the file type such as .js, .json, or .node. Step 3: Compilation For JavaScript files, Node wraps the module inside an IIFE (Immediately Invoked Function Expression). This creates the familiar function wrapper: (function (exports, require, module, __filename, __dirname) { // module code }); Step 4: Evaluation The wrapped function is executed, and whatever is assigned to module.exports becomes the exported value. Step 5: Caching Finally, the module is cached. If the same module is required again, Node returns the cached version instead of executing it again, which improves performance. Understanding this process helped me better appreciate how Node.js manages modules internally. If you're learning backend development with Node.js, exploring the runtime source code can reveal many interesting insights about how JavaScript actually runs behind the scenes. #NodeJS #JavaScript #BackendDevelopment #WebDevelopment #OpenSource #SoftwareEngineering
To view or add a comment, sign in
-
-
Have you ever observed anything strange in Node.js? It runs on a single thread. But somehow, it can process thousands of requests at the same time. How? For one, when I realized this, it did not make sense. One thread. Thousands of users. No crashes? And that’s what really happens behind the scenes. Node.js doesn't wait. When a request comes: • Database call? → Sent to the system • File read? → Sent to the system • Network request? → Sent to the system And Node.js immediately moves on to the next request. Once the result is ready, Node.js is notified. This is known as the **Event Loop**. Node.js is not fast because it does everything itself. Node.js is fast because it “knows how to not wait.” "That’s the real power." Good developers can write code. More knowledgeable developers are aware of the performance of the code. At times, it's not about adding more code. Sometimes it is about letting Node.js do its job. #NodeJs #BackendDevelopment #Javascript #EventLoop #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
Today I took a deeper dive into Node.js internals, specifically exploring how the require() function actually works behind the scenes. Earlier, I used require() simply to import modules. But today, I went beyond surface-level usage and understood how Node.js executes code internally when we load a module. What I explored: 🔹 How require() loads a module step by step Resolves the file path Checks the module cache Wraps the code inside a function Executes the file in its own module scope Returns module.exports 🔹 The Module Wrapper Function Node.js does not execute your file directly. It wraps it internally like this: (function (exports, require, module, __filename, __dirname) { // Your actual code here }); This explains: Why variables are not global by default How module.exports works Why __dirname and __filename are available 🔹 Module Caching Once a module is loaded, Node.js caches it. If you require() the same file again, it does not execute again — it returns the cached version. This improves performance and prevents duplicate execution. 🔹 Execution Flow When Node starts: It creates a main module It executes top-level code Each require() creates a new module context Modules maintain their own scope 💡 Key realization: require() is not just an import statement — it is a complete module loading system involving resolution, wrapping, execution, and caching. Understanding this gave me clarity on: Scope isolation in Node.js Performance behavior Circular dependencies How large backend applications are structured This deep dive helped me see Node.js not just as a runtime, but as a carefully engineered system designed for modular and scalable applications. Node_Git_Repo: https://lnkd.in/gz5523ZV #NodeJS #JavaScript #Require #ModuleSystem #BackendDevelopment #LearningJourney
To view or add a comment, sign in
-
🔥 Node.js Developers: Do you really understand exports vs module.exports? This confusion trips up even experienced developers. Let me clear it up once and for all 👇 When you run this code: console.log(module.exports === exports); // true They're equal! So what's the difference? Here's the key: At the start of every module, Node.js does this: const module = { exports: {} }; const exports = module.exports; exports is just a reference (shorthand) pointing to the same object as module.exports. Think of it like this JavaScript example: const user = { address: { city: "Mumbai" } }; let address = user.address; address.pinCode = 400001; console.log(user.address.pinCode); // 400001 When we modify address, user.address changes too because they point to the same memory location. The same applies to exports! ✅ This WORKS: exports.add = (a, b) => a + b; // You're mutating the shared object ✅ This WORKS: module.exports = class User {}; // You're directly replacing what gets exported ❌ This BREAKS: exports = { name: "Sharvil" }; // You broke the reference! // module.exports still points to {} 🎯 The Critical Rule: Only module.exports gets returned when you require() a module. The exports variable is just a convenience. 💡 Best Practice: - Use exports for multiple properties. - Use module.exports for single classes/functions. - Never reassign exports directly. Have you been bitten by this before? Drop a comment with your experience! 📚 Currently learning "Fundamentals of Node.js" as part of Anurag Singh's "Complete Backend with Node.js" course. 🙌 Thanks Anurag Singh for explaining core concepts so clearly. #NodeJS #JavaScript #WebDevelopment #Programming #CodingTips #BackendDevelopment #CommonJS
To view or add a comment, sign in
-
When building APIs with Node.js and Express.js, the way you call APIs can significantly impact performance. A common mistake many developers make is calling APIs one by one (sequentially) when the requests are independent. 1️⃣ Sequential API Calls (One by One) In this approach, each API waits for the previous one to complete. JavaScript const user = await getUser(); const orders = await getOrders(); const payments = await getPayments(); Here, every request blocks the next one. If each API takes 500ms, the total time becomes: 500ms + 500ms + 500ms = 1500ms This increases response time and slows down your backend. 2️⃣ Parallel API Calls (All at Once) If the APIs are independent, you can run them in parallel using Promise.all(). JavaScript const [user, orders, payments] = await Promise.all([ getUser(), getOrders(), getPayments() ]); Now all requests run simultaneously, so the total time becomes roughly: ~500ms instead of 1500ms Why this matters Optimizing API calls can dramatically improve: • Backend performance • API response time • User experience • Server efficiency Simple Rule Use sequential calls only when one API depends on another. Otherwise, use parallel execution with Promise.all(). Small backend optimizations like this can make a huge difference at scale. #NodeJS #ExpressJS #BackendDevelopment #JavaScript #API #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
[EN] .js, .mjs, .cjs - what do they actually mean? At first glance, these extensions can feel confusing. In practice, they simply tell Node how to interpret your file. Behind the scenes, two different module systems exist. ⌛ Why are there still two systems? 2009 : Creation of Node.js JavaScript didn’t yet have a standardized module system. Node introduced CommonJS to structure imports and exports on the server side. 2015 : Standardization of ES Modules (ESM) A formal, language-level module system designed to work in both browsers and servers. 2020 : Official ES Module support in Node.js By then, the ecosystem already contained millions of CommonJS packages. An immediate full migration wasn’t realistic. 👉 As a result, both systems still coexist today. ES Modules are gradually becoming the default standard. CommonJS remains widely used across the existing ecosystem. 💻 What changes in practice? 🧓 CommonJS - const x = require("module"); module.exports = x; - Synchronous loading - Historically, very widespread 👶 ES Modules - import x from "module"; export default x; - Standardized syntax - Works in browsers and Node 📄 The file extensions .js It depends on your project configuration: If package.json contains "type": "module" → treated as ES Module Otherwise → treated as CommonJS .mjs Always interpreted as an ES Module. .cjs Always interpreted as a CommonJS module. #JavaScript #NodeJS #WebDevelopment #FullStackDevelopment #SoftwareEngineering #Coding #ESModules #CommonJS #Node #FrontendDevelopment #DevCommunity
To view or add a comment, sign in
-
🚨 One API Design Mistake I Still See in Many Node.js / JavaScript Projects While reviewing some backend code recently, I noticed a pattern that silently makes APIs harder to maintain and scale. Many developers design APIs like this: POST /getUserData POST /deleteUser POST /updateUserInfo POST /createNewUser At first glance it works… But long term it becomes a maintenance nightmare. Why? ❌ Everything is POST ❌ Endpoint names contain actions ❌ Inconsistent structure ❌ Harder to scale and document ❌ Breaks REST principles This approach turns your API into an action-based system instead of a resource-based system. 💡 A Better Approach (RESTful Design) Design APIs around resources, not actions. Example: GET /users GET /users/123 POST /users PUT /users/123 DELETE /users/123 Now your API becomes: ✅ Predictable ✅ RESTful ✅ Scalable ✅ Easier for frontend teams ✅ Cleaner documentation 🔑 A Rule I Follow in Backend Development Endpoints = Resources HTTP Methods = Actions Resource → /users Action → GET, POST, PUT, DELETE Once you follow this rule, your APIs instantly become cleaner and easier to extend. ⚡ Small API Design Decisions = Huge Long-Term Impact Great backend systems are not just about writing code. They are about designing systems that remain clean even after thousands of requests and hundreds of new features. Curious to know 👇 What is the most common API design mistake you've seen in real projects? Let's discuss in the comments. #javascript #nodejs #backenddevelopment #restapi #webdevelopment #softwareengineering #coding #developers #programming #tech
To view or add a comment, sign in
-
-
🔁 Understanding require() & Modules in Node.js When starting with Node.js, one concept that often feels confusing is how modules work. Let’s simplify it 👇 📦 1. require() in Node.js require() is used to import functionality from another file/module. const math = require('./math'); This allows you to reuse code instead of rewriting logic. 🧩 2. Modules Protect Their Scope Every module in Node.js has its own private scope. ✅ Variables & functions inside a module ❌ Are NOT leaked globally This prevents naming conflicts and keeps code maintainable. 📤 3. module.exports (CommonJS – CJS) To share code from a module: module.exports = function add(a, b) { return a + b; }; Then import it using require(). ⚡ 4. ES Modules (Modern Alternative) Instead of: const x = require('module'); We now use: import x from 'module'; ES Modules are cleaner and align with modern JavaScript. 💡 Key Takeaway Modules help you: ✔ Organize code ✔ Avoid global pollution ✔ Build scalable applications #NodeJS #JavaScript #WebDevelopment #Backend #CodingConcepts
To view or add a comment, sign in
-
Node.js is single-threaded. Then how does it handle thousands of requests at the same time? It’s not magic. It’s the event loop. Here’s the simple idea. Blocking code ❌ - Waits for a task to finish before moving on. - One request can stop everything. - Common in traditional synchronous systems. Non-blocking code 🚀 - Starts a task and moves to the next one. - Doesn’t wait for I/O operations (DB, API, file). - Handles many requests efficiently. When Node.js receives a request: 1. It sends I/O tasks to the system (like DB or network). 2. It doesn’t wait for them to finish. 3. It keeps processing other requests. 4. When the task completes, the event loop picks the callback. Instead of many threads, Node.js uses asynchronous I/O. Without async: “Wait until this finishes.” With async: “Tell me when it's done.” Good backend systems handle requests. Great backend systems never block the event loop. What are your favourite ways to avoid blocking in Node.js projects? 👍 Like, 💬 comment, and ➕ follow for more posts like this. 🙏 Thanks for reading. Have a great day 🌱 #NodeJS #Backend #JavaScript #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Ever wondered why your Node.js code executes in a "weird" order? Understanding the Event Loop priority is a hallmark of a Senior Developer. If you’ve ever been confused by why a Promise resolves before a setTimeout, this breakdown is for you. Here is how Node.js prioritizes your code: ⚡ Bucket 1: The "Interrupters" (Microtasks) These don't wait for the loop phases. They jump to the front of the line as soon as the current operation finishes. process.nextTick(): The ultimate priority. It runs even before Promises. Promises (.then/await): Runs immediately after the current task and before the loop moves to the next phase. ⚡ Bucket 2: The "Phased" Loop (Macrotasks) This is the heart of the Event Loop managed by libuv. It moves in specific stages: 1️⃣ Timers Phase: Handles setTimeout and setInterval. 2️⃣ Poll Phase: The engine room. This is where Node.js handles I/O (Network, DB, File System) and "waits" for data. 3️⃣ Check Phase: This is where setImmediate lives. It’s designed to run specifically after I/O events. 💡 Key Takeaway: Inside an I/O callback, setImmediate will always run before a 0ms setTimeout. #Nodejs #BackendDevelopment #Javascript #SoftwareEngineering
To view or add a comment, sign in
Explore related topics
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