npm, Packages, and Project Structure
Learn how Node.js projects are initialized, how npm manages dependencies, how package.json works, and how to structure maintainable applications.
npm and package.json
npm is the default package manager commonly used with Node.js. A package.json file describes a project, including its name, version, scripts, dependencies, development dependencies, and module configuration.
The scripts section provides convenient commands such as npm run dev, npm test, and npm start.
mkdir node-app
cd node-app
npm init -y
npm install express
npm install --save-dev nodemonpackage.json, install Express as a production dependency, and install Nodemon as a development dependency.- Production dependencies belong in
dependencies. - Build, test, and development tools usually belong in
devDependencies. - Use npm scripts to standardize project commands.
Which file defines npm scripts and project dependencies?
Semantic Versioning and Lockfiles
Packages commonly follow semantic versioning using the MAJOR.MINOR.PATCH format. A major version can contain breaking changes, a minor version generally adds backward-compatible functionality, and a patch version usually contains backward-compatible fixes.
Lockfiles such as package-lock.json record the exact dependency tree installed for a project. This improves reproducibility between environments.
For applications, commit your lockfile so CI and production installations can reproduce the dependency tree.
npm install
npm ci
npm install express@latest
npm outdatednpm install installs dependencies and may update the lockfile. npm ci performs a clean, lockfile-based installation and is preferred for CI environments.- Semantic versioning communicates compatibility expectations.
- Lockfiles make dependency installations reproducible.
- Use
npm cifor deterministic CI installations.
Which command is generally preferred for a clean CI installation?
Structuring a Node.js Application
A maintainable Node.js application separates responsibilities instead of placing everything inside one large file. A common architecture separates routes, controllers, services, repositories, models, middleware, configuration, utilities, and tests.
For larger applications, organize code around business domains rather than creating extremely large technical folders. The goal is clear ownership of responsibilities and easy testing.
- Keep HTTP concerns separate from business logic.
- Services should contain reusable business operations.
- Architecture should reduce coupling rather than add unnecessary abstraction.
Which layer should normally contain business rules?