Table of Contents
This cheatsheet provides a comprehensive overview of Node.js, covering its core concepts, modules, and common use cases. It includes code snippets and explanations to help you quickly grasp and apply Node.js in your projects.
Introduction to Node.js
Node.js is a runtime environment that allows you to execute JavaScript code server-side. It’s built on Chrome’s V8 JavaScript engine, making it incredibly fast and efficient. Node.js uses a non-blocking, event-driven I/O model, which makes it ideal for building scalable and high-performance network applications.
- Key Features:
- JavaScript Runtime: Executes JavaScript outside the browser.
- Non-blocking I/O: Handles multiple requests concurrently without waiting for each one to complete.
- Event-driven Architecture: Uses callbacks and events to manage asynchronous operations.
- NPM (Node Package Manager): A vast repository of open-source libraries and tools.
- Cross-platform: Runs on Windows, macOS, and Linux.
Core Modules
Node.js comes with a rich set of built-in modules. Here are some of the most important ones:
http
: For creating web servers and handling HTTP requests.
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
});
const port = 3000;
server.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
fs
(File System): For working with files and directories.
const fs = require('fs');
// Asynchronous file read
fs.readFile('myfile.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
// Synchronous file write (use with caution)
try {
fs.writeFileSync('newfile.txt', 'This is some text.');
console.log('File written successfully.');
} catch (err) {
console.error(err);
}
path
: For working with file paths.
const path = require('path');
const filePath = '/path/to/my/file.txt';
console.log(path.basename(filePath)); // Output: file.txt
console.log(path.dirname(filePath)); // Output: /path/to/my
console.log(path.join(__dirname, 'data', 'file.json')); // Construct path
url
: For parsing and working with URLs.
const url = require('url');
const myURL = new URL('https://www.example.com/path?query=string');
console.log(myURL.hostname); // Output: www.example.com
console.log(myURL.pathname); // Output: /path
console.log(myURL.search); // Output: ?query=string
os
: Provides information about the operating system.
const os = require('os');
console.log(os.platform()); // Output: win32, darwin, linux, etc.
console.log(os.cpus()); // Information about CPU cores
console.log(os.totalmem()); // Total system memory
events
: For working with custom events.
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', (data) => {
console.log('Event occurred:', data);
});
myEmitter.emit('event', { message: 'Hello!' });
stream
: For handling streaming data (important for large files and network communication).
const fs = require('fs');
const readStream = fs.createReadStream('largefile.txt', 'utf8');
readStream.on('data', (chunk) => {
console.log('Received chunk:', chunk);
});
readStream.on('end', () => {
console.log('Finished reading file.');
});
readStream.on('error', (err) => {
console.error('Error reading file:', err);
});
zlib
: For compression and decompression (gzip, deflate, etc.).
const zlib = require('zlib');
const fs = require('fs');
const gzip = zlib.createGzip();
const inp = fs.createReadStream('input.txt');
const out = fs.createWriteStream('input.txt.gz');
inp.pipe(gzip).pipe(out);
NPM (Node Package Manager)
NPM is essential for managing dependencies in your Node.js projects.
npm init
: Initializes a new Node.js project, creating apackage.json
file.npm install <package_name>
: Installs a package and adds it topackage.json
. Use--save-dev
for development dependencies.npm install
: Installs all dependencies listed inpackage.json
.npm update <package_name>
: Updates a package to its latest version.npm uninstall <package_name>
: Uninstalls a package.npm start
: Runs the script defined in thestart
field ofpackage.json
.package.json
: A file that contains metadata about your project, including dependencies, scripts, and other information. Crucially, it manages project dependencies.
Asynchronous Programming
Node.js relies heavily on asynchronous programming. Here are the primary ways to handle it:
- Callbacks: The traditional way, but can lead to “callback hell” for complex operations.
fs.readFile('file1.txt', 'utf8', (err, data1) => {
if (err) { /* handle error */ }
fs.readFile('file2.txt', 'utf8', (err, data2) => {
if (err) { /* handle error */ }
// ... process data1 and data2 ...
});
});
- Promises: A cleaner way to handle asynchronous operations.
const fsPromises = require('fs').promises; // Available in Node.js v10+
fsPromises.readFile('file1.txt', 'utf8')
.then(data1 => fsPromises.readFile('file2.txt', 'utf8').then(data2 => { /* process data1 and data2 */ }))
.catch(err => { /* handle error */ });
- Async/Await: Makes asynchronous code look synchronous.
async function readFileData() {
try {
const data1 = await fsPromises.readFile('file1.txt', 'utf8');
const data2 = await fsPromises.readFile('file2.txt', 'utf8');
// ... process data1 and data2 ...
} catch (err) {
/* handle error */
}
}
readFileData();
Event Loop
The event loop is the core of Node.js’s non-blocking I/O model. It continuously monitors for events (like file I/O completion or network requests) and executes their associated callbacks. Understanding the event loop is crucial for writing efficient Node.js applications. It operates in phases (timers, pending callbacks, idle/poll, check, close callbacks) to handle events in a specific order.
Express.js (Web Framework)
Express.js is a popular web framework for Node.js that simplifies building web applications and APIs.
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
- Middleware: Functions that run before the route handlers.
// Example middleware
app.use((req, res, next) => {
console.log('Middleware executed.');
next(); // Important: Call next() to pass control to the next middleware or route handler
});
- Routing: Defining how the application responds to different HTTP requests.
- Request and Response Objects:
req
contains information about the incoming request, andres
is used to send the response.
Databases
Node.js can connect to various databases:
- MongoDB (using Mongoose or the MongoDB driver)
// ... (Previous code)
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('MongoDB connection error:', err));
const userSchema = new mongoose.Schema({
name: String,
email: String,
});
const User = mongoose.model('User', userSchema);
// Example: Creating a new user
const newUser = new User({ name: 'John Doe', email: '[email address removed]' });
newUser.save()
.then(user => console.log('User saved:', user))
.catch(err => console.error('Error saving user:', err));
// Example: Finding users
User.find({})
.then(users => console.log('Users:', users))
.catch(err => console.error('Error finding users:', err));
- PostgreSQL (using pg):
const { Pool } = require('pg');
const pool = new Pool({
user: 'your_user',
host: 'localhost',
database: 'your_database',
password: 'your_password',
port: 5432, // Default PostgreSQL port
});
pool.query('SELECT * FROM users', (err, res) => {
if (err) {
console.error(err);
} else {
console.log(res.rows);
}
pool.end(); // Close the connection pool
});
// Using async/await:
async function getUsers() {
try{
const client = await pool.connect()
const result = await client.query('SELECT * FROM users')
const users = result.rows
client.release()
return users
} catch (error){
console.error("Error fetching users:", error)
} finally {
pool.end()
}
}
getUsers().then(users => console.log("Users fetched:", users))
- MySQL (using mysql2):
const mysql = require('mysql2/promise'); // Use the promise-based API
async function connectToMySQL() {
try {
const connection = await mysql.createConnection({
host: 'localhost',
user: 'your_user',
password: 'your_password',
database: 'your_database',
});
const [rows] = await connection.execute('SELECT * FROM users');
console.log('Users:', rows);
connection.end();
} catch (error) {
console.error('Error connecting to MySQL:', error);
}
}
connectToMySQL();
Testing
Testing is crucial for ensuring the quality of your Node.js applications. Popular testing frameworks include:
- Jest: A popular and comprehensive testing framework.
- Mocha: Another widely used testing framework.
- Supertest: For testing HTTP requests in Express.js applications.
// Example using Jest and Supertest (example test for the Express app above)
const request = require('supertest');
const app = require('./app'); // Your Express app
describe('GET /', () => {
it('should return Hello, Express!', async () => {
const res = await request(app).get('/');
expect(res.statusCode).toEqual(200);
expect(res.text).toEqual('Hello, Express!');
});
});
describe('GET /users/:id', () => {
it('should return the correct user ID', async () => {
const res = await request(app).get('/users/123')
expect(res.statusCode).toEqual(200)
expect(res.text).toEqual('User ID: 123')
})
})
Security Best Practices
- Input Validation: Sanitize and validate all user input to prevent injection attacks (e.g., SQL injection, cross-site scripting).
- Authentication and Authorization: Implement secure authentication and authorization mechanisms to protect your application’s 1 resources. Use established libraries like Passport.js. 1. www.psdly.com www.psdly.com
- HTTPS: Always use HTTPS to encrypt communication between the client and server.
- Rate Limiting: Implement rate limiting to prevent abuse and protect against denial-of-service attacks.
- Dependency Management: Keep your dependencies up to date to patch security vulnerabilities. Regularly audit your
package.json
file. - Error Handling: Don’t expose sensitive information in error messages. Log errors appropriately.
- Helmet.js: Use Helmet.js middleware in Express.js for setting various HTTP headers to enhance security.
Deployment
Node.js applications can be deployed to various platforms:
- Cloud Platforms: AWS, Google Cloud, Azure, Heroku, Netlify, Vercel, etc.
- Containerization: Docker and Kubernetes for containerized deployments.
- PM2: A process manager for production deployments, providing features like process monitoring, automatic restarts, and load balancing.
Performance Optimization
- Profiling: Use profiling tools to identify performance bottlenecks.
- Caching: Implement caching strategies to reduce database load and improve response times.
- Load Balancing: Distribute traffic across multiple instances of your application.
- Asynchronous Operations: Take full advantage of Node.js’s asynchronous nature.
- Gzip Compression: Use gzip compression to reduce the size of responses.
- Keep-Alive: Enable keep-alive connections to reduce latency.
Debugging
console.log()
: A basic but useful debugging tool.- Node.js Debugger: Use the built-in Node.js debugger or tools like Chrome DevTools for more advanced debugging.
- Debuggers in IDEs: Most IDEs (VS Code, WebStorm, etc.) have built-in debuggers for Node.js.
ES Modules
Node.js supports ES modules (using import
and export
) alongside CommonJS modules (require
). Use the .mjs
file extension or add "type": "module"
to your package.json
to use ES modules.
// mymodule.mjs
export function myFunction() {
return "Hello from ES module!";
}
// main.mjs
import { myFunction } from './mymodule.mjs';
console.log(myFunction());
Node.js Versions and NVM
Node Version Manager (NVM) is a helpful tool for managing multiple Node.js versions on your system. This is essential for working on different projects that may require specific Node.js versions.
Further Learning
- Node.js Official Documentation: The best resource for learning about Node.js.
- Express.js Documentation: For learning about the Express.js framework.
- MDN Web Docs: Excellent documentation for JavaScript and web technologies.
- Online Courses and Tutorials: Platforms like Udemy, Coursera, and freeCodeCamp offer many Node.js courses.
This cheatsheet provides a solid foundation for working with Node.js. Remember to consult the official documentation and explore the vast ecosystem of Node.js libraries to deepen your knowledge and build more complex applications. Practice is key! Work on projects, experiment with different modules, and contribute to open-source projects to become proficient in Node.js development. Remember to use this as a starting point and continue to explore the rich ecosystem of Node.js. Good luck!