Node.js: Code Outside the Browser / Working with Modules

What are modules?

📦 What Are Modules?

Node.js treats every script file as its own module. Wrapping logic inside individual files keeps variables and functions scoped locally — nothing leaks out unless you explicitly export it.

This is what lets you build large apps without variables from one file quietly clashing with another.


👀 Types of Modules

  • 🏠 Local modules — the ones you write yourself, inside your app

  • ⚙️ Built-in modules — ship with Node.js out of the box

  • 🤝 Third-party modules — written by other developers, usually installed via npm


⚙️ Built-in Modules

Also called core modules — they come bundled with Node.js, but you still need to import them before use.

  • fs — File System: read, write, or modify files

  • http — create a server and handle HTTP requests

  • path — work with file and directory paths

  • os — get system info (OS type, memory, CPU, etc.)

  • url — parse and format URLs

  • events — handle events with the EventEmitter class

  • crypto — encryption, hashing, and more


🤝 Third-Party Modules

Built by other developers and shared publicly — usually through npm (Node Package Manager). Install them and use them in your app to skip writing common functionality from scratch.

🧑‍💻 Examples

  • express — web framework for building APIs & web apps

  • mongoose — work with MongoDB easily

  • dotenv — load environment variables from .env files

  • lodash — utility functions for arrays, strings, objects

  • chalk — add color and style to terminal output

📚 Why Use Them?

  • Skip reinventing the wheel

  • Get community-tested, well-documented, actively maintained code

  • Speeds up development and adds powerful features fast


Next up: the two ways Node.js actually loads these modules — CommonJS and ES Modules.