Day 02 - MERN: Mastering NPM and Express.js
Welcome to the next phase of backend development, where we organize our project dependencies and set up our first web server using NPM and Express.js.
1. The Node Package Manager (NPM)
NPM is the default marketplace and package manager for Node.js, allowing you to install pre-written code, manage project dependencies, and execute scripts.
- Initialization: Running
npm init -ygenerates apackage.jsonfile. This file acts as the blueprint of your project, storing metadata, custom script commands, and a list of all required packages. - NPM Scripts: Instead of typing long execution commands in the terminal, you can define shortcuts in
package.json(e.g., mapping"start": "node index.js"). Runningnpm startexecutes it automatically, standardizing the workflow for anyone working on the project.
2. Managing Dependencies
When you run a command like npm install express, NPM downloads the package and alters your project structure:
- node_modules: This folder contains all the raw code for your installed packages. Because it is massive and can be instantly regenerated by running
npm install, it should never be pushed to version control. Always add it to your.gitignorefile. - package-lock.json: This file locks down the exact version numbers of your dependencies. It guarantees that if another developer clones your project, they install the exact same package versions, preventing bugs caused by mismatched software updates.
3. CommonJS vs. ES Modules
Node.js supports two different module systems for sharing code between files:
- CommonJS: The traditional Node standard that uses
require()to import files andmodule.exportsto export them. - ES Modules: The modern JavaScript standard utilizing
importandexport. To enable this modern syntax in a Node environment, you must explicitly add"type": "module"to yourpackage.json.
4. Building with Express.js
Writing a server from scratch with pure Node.js requires manually handling routing, request parsing, and error management. Express.js is a minimal web framework that abstracts this heavy lifting away.
- The Framework Flow: Remember the golden rule: you call a library, but a framework calls you. Express dictates the application’s flow by intercepting incoming browser requests and funneling them through a pipeline of middleware and route handlers before returning a response.
- Unopinionated Freedom: Unlike rigid frameworks (like Django or Spring Boot), Express does not force a specific folder structure, database choice, or authentication method on you. It provides powerful routing capabilities while leaving the architectural design entirely in your hands.
Comments
Questions, corrections, and practical takeaways are welcome here.