Node.js’s module system and npm (Node Package Manager) are what make it so powerful. This guide will help you master these fundamental concepts.
1. Understanding Modules
Core Modules
Built into Node.js installation:
fs
– File system operationshttp
– HTTP server/clientpath
– File path utilitiesos
– OS-related utilities
Custom Modules
Create your own reusable code:
// greet.js
module.exports = function(name) {
return `Hello ${name}!`;
};
2. Module Usage Patterns
Importing Core Modules
const fs = require('fs');
Importing Local Modules
const greet = require('./greet');
console.log(greet('Developer'));
ES Modules (Modern Approach)
import fs from 'fs';
import greet from './greet.js';
3. package.json Deep Dive
This file is the heart of every Node.js project. Here’s what you need to know:
Key Field | Purpose | Example |
---|---|---|
dependencies | Production required packages | "express": "^4.18.2" |
devDependencies | Development-only packages | "nodemon": "^2.0.22" |
scripts | Custom command shortcuts | "start": "node app.js" |
4. Essential npm Commands
Package Installation
npm install package
– Local installnpm install -g package
– Global installnpm install --save-dev package
– Dev dependency
Project Management
npm init
– Create new projectnpm update
– Update packagesnpm audit
– Security check
5. Semantic Versioning Explained
Node.js packages follow semver (semantic versioning):
"dependencies": {
"express": "^4.18.2", // Compatible with 4.x.x
"lodash": "~4.17.21", // Compatible with 4.17.x
"mongoose": "5.13.16" // Exact version only
}
Version Symbols: ^
= minor/patch updates, ~
= patch updates only, no symbol = exact version
6. Creating Your Own Module
Step-by-step guide to publishing:
- Create your module code
- Add proper
package.json
- Login to npm:
npm login
- Publish:
npm publish
7. Best Practices
- Always specify exact versions in production (
npm install --save-exact
) - Use
.npmignore
to exclude unnecessary files - Regularly run
npm outdated
andnpm update
- Consider using
yarn
orpnpm
for large projects
Next: Building Your First Node.js Server →
npm Cheat Sheet
npm list --depth=0
– View installed packagesnpm view package versions
– See available versionsnpm uninstall package
– Remove a packagenpm ci
– Clean install (for CI/CD)