Installing and Using Packages
Now that you understand npm and package.json, let's learn how to find, install, and use packages in your Node.js projects. The npm ecosystem has packages for almost everything—from web frameworks to utility libraries.
Finding Packages
Where to Look
- npmjs.com: The official registry
- GitHub: Check stars, issues, last commit
- npm search:
npm search <keyword> - Recommendations: Blogs, tutorials, community
Evaluating Packages
Before installing, check:
| Factor | Good Sign | Red Flag |
|---|---|---|
| Weekly downloads | More than 10,000 | Less than 100 |
| Last publish | Within 6 months | Over 2 years ago |
| Open issues | Few, addressed | Hundreds, ignored |
| Dependencies | Minimal | Excessive |
| Documentation | Complete | Missing |
| Types | Included or @types | None |
Installing Packages
Basic Installation
# Install and save to dependencies
npm install lodash
# Install specific version
npm install lodash@4.17.21
# Install multiple packages
npm install express cors helmet
Install as Dev Dependency
npm install --save-dev jest
npm install -D typescript eslint
Install Globally
npm install -g nodemon
npm install -g typescript
Install from Different Sources
# From npm registry (default)
npm install express
# From GitHub
npm install github:user/repo
# From local folder
npm install ../my-local-package
# From tarball
npm install package.tar.gz
Loading JavaScript Playground...
Using Installed Packages
CommonJS (require)
// Import entire package
const lodash = require('lodash');
const _ = require('lodash'); // Common alias
// Import specific functions
const { debounce, throttle } = require('lodash');
// Use the package
const result = _.chunk([1, 2, 3, 4, 5], 2);
console.log(result); // [[1, 2], [3, 4], [5]]
ES Modules (import)
// Import default export
import express from 'express';
// Import named exports
import { v4 as uuidv4 } from 'uuid';
// Import all as namespace
import * as lodash from 'lodash';
// Use the package
const app = express();
const id = uuidv4();
Common Packages in Action
Express - Web Framework
const express = require('express');
const app = express();
app.use(express.json());
app.get('/', (req, res) => {
res.json({ message: 'Hello World' });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Lodash - Utilities
const _ = require('lodash');
// Array operations
_.chunk([1, 2, 3, 4, 5], 2); // [[1,2], [3,4], [5]]
_.uniq([1, 1, 2, 2, 3]); // [1, 2, 3]
_.shuffle([1, 2, 3, 4, 5]); // Random order
// Object operations
_.pick({ a: 1, b: 2, c: 3 }, ['a', 'c']); // { a: 1, c: 3 }
_.omit({ a: 1, b: 2, c: 3 }, ['b']); // { a: 1, c: 3 }
// Collection operations
_.groupBy([6.1, 4.2, 6.3], Math.floor); // { '4': [4.2], '6': [6.1, 6.3] }
uuid - Unique IDs
const { v4: uuidv4, v1: uuidv1 } = require('uuid');
const id1 = uuidv4(); // Random UUID
const id2 = uuidv1(); // Timestamp-based UUID
console.log(id1); // 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'
dotenv - Environment Variables
// .env file
// PORT=3000
// DATABASE_URL=mongodb://localhost/mydb
require('dotenv').config();
console.log(process.env.PORT); // '3000'
console.log(process.env.DATABASE_URL); // 'mongodb://localhost/mydb'
Loading JavaScript Exercise...
Managing Installed Packages
Check Installed Packages
# List all installed packages
npm list
# List top-level only
npm list --depth=0
# Check for outdated packages
npm outdated
# View package info
npm view express
npm view express versions
Update Packages
# Update all packages (within semver range)
npm update
# Update specific package
npm update lodash
# Update to latest (ignoring semver)
npm install lodash@latest
Remove Packages
# Uninstall package
npm uninstall lodash
# Uninstall dev dependency
npm uninstall -D jest
# Remove unused packages
npm prune
Security
# Check for vulnerabilities
npm audit
# Fix vulnerabilities
npm audit fix
# Force fix (may break things)
npm audit fix --force
npx - Execute Package Binaries
Run packages without installing:
# Run create-react-app without installing
npx create-react-app my-app
# Run specific version
npx cowsay@1.5.0 "Hello"
# Run local package binary
npx jest --watch
Common Project Setup
Web API Project
mkdir my-api && cd my-api
npm init -y
npm install express cors helmet dotenv
npm install -D nodemon jest
{
"scripts": {
"start": "node src/index.js",
"dev": "nodemon src/index.js",
"test": "jest"
}
}
TypeScript Project
mkdir ts-project && cd ts-project
npm init -y
npm install -D typescript @types/node tsx
npx tsc --init
Best Practices
1. Lock Dependencies
Always commit package-lock.json:
# Use exact versions for production
npm ci # Installs from lock file
2. Separate Dependencies
{
"dependencies": {
"express": "^4.18.2" // Needed in production
},
"devDependencies": {
"jest": "^29.0.0" // Only for development
}
}
3. Keep Packages Updated
# Check outdated regularly
npm outdated
# Update carefully, test after
npm update
4. Audit Security
# Make it a habit
npm audit
Key Takeaways
- Use npmjs.com to find and evaluate packages
- Install with
npm install <package> - Use
-Dfor dev dependencies,-gfor global - Import with
require()orimport - Use
npm outdatedto check for updates - Use
npm auditto check security - Commit
package-lock.json, nevernode_modules
Summary
You've learned how to find, install, and use npm packages in your Node.js projects. You know how to manage dependencies, keep them updated, and maintain security. The npm ecosystem is vast—there's likely a package for almost anything you need to build.
In the next module, you'll learn about environment variables and configuration management in Node.js.
Quiz
Question 1 of 617% Complete
0 of 6 questions answered

