Node.js is a powerful runtime environment that allows developers to execute JavaScript code outside the browser, making it ideal for building scalable, fast, and efficient server-side applications. This Node Js cheatsheet table highlights essential concepts, frequently used modules, and practical examples to make Node.js development simpler and more productive.
On This Page
Table of Contents
Nodejs CheatSheet Table: Key Concepts and Syntax
Concept | Syntax / Module | Example / Notes |
---|---|---|
Initialize Project | npm init or npm init -y | Creates package.json . Use -y to skip questions. |
Import Module | const module = require('module'); | Example: const fs = require('fs'); |
Export Module | module.exports = object/function; | Example: module.exports = { greet: () => console.log('Hello') }; |
HTTP Server | require('http'); | Example: http.createServer((req, res) => { res.end('Hello'); }).listen(3000); |
Express Server | require('express'); | Example: const app = express(); app.get('/', (req, res) => res.send('Hello')); |
Asynchronous File Read | fs.readFile('file.txt', callback); | Example: fs.readFile('file.txt', 'utf8', (err, data) => console.log(data)); |
Synchronous File Read | fs.readFileSync('file.txt'); | Use cautiously; blocks execution until the file is read. |
Write File | fs.writeFile('file.txt', data, callback); | Asynchronously write data to a file. |
URL Parsing | require('url'); | Example: const url = new URL('https://example.com'); console.log(url.hostname); |
Query Strings | require('querystring'); | Parse and stringify query strings: querystring.parse('a=1&b=2'); |
Event Emitter | require('events'); | Example: const EventEmitter = require('events'); const emitter = new EventEmitter(); |
Timers | setTimeout , setInterval | Example: setTimeout(() => console.log('Hello'), 1000); |
Path Module | require('path'); | Example: path.join(__dirname, 'folder', 'file.txt'); |
OS Module | require('os'); | Get system information: os.platform(); os.freemem(); |
Process Module | process.argv | Access command-line arguments: node app.js arg1 arg2 . |
Child Process | require('child_process'); | Example: child_process.exec('ls', (err, stdout) => console.log(stdout)); |
Stream – Read | fs.createReadStream('file.txt'); | Stream data for large files: readStream.on('data', chunk => console.log(chunk)); |
Stream – Write | fs.createWriteStream('file.txt'); | Pipe readable streams to writable streams: readStream.pipe(writeStream); |
Buffer | Buffer.from(string) | Example: const buf = Buffer.from('Hello'); |
Cluster | require('cluster'); | Create multiple processes for better performance. |
Environment Variables | process.env.VAR_NAME | Example: process.env.PORT; Set with PORT=3000 node app.js . |
Middleware (Express) | app.use((req, res, next) => { next(); }); | Example: app.use(express.json()); |
Routing (Express) | app.get , app.post , app.put , app.delete | Example: app.post('/route', (req, res) => res.send('Posted')); |
Body Parsing | app.use(express.json()); | Parse JSON body in requests. |
Database Connection | require('mongoose'); | Example: mongoose.connect('mongodb://localhost:27017/db'); |
API Fetch | require('axios'); | Example: axios.get('https://api.example.com').then(res => console.log(res.data)); |
WebSocket | require('ws'); | Example: const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); |
JWT Authentication | require('jsonwebtoken'); | Example: jwt.sign(payload, secret, options); |
Session Management | require('express-session'); | Example: app.use(session({ secret: 'key', resave: false })); |
CORS Handling | require('cors'); | Example: app.use(cors()); |
Static Files | app.use(express.static('public')); | Serve static files like HTML, CSS, and JS. |
Helmet (Security) | require('helmet'); | Example: app.use(helmet()); Enhances security by setting HTTP headers. |
Rate Limiting | require('express-rate-limit'); | Example: app.use(rateLimit({ windowMs: 15 * 60 * 1000, max: 100 })); |
Error Handling | app.use((err, req, res, next) => { res.status(500).send(err.message); }); | Centralized error handling. |
Testing | require('mocha'); , require('chai'); | Example: describe('Test Suite', () => { it('should pass', () => { }); }); |
Promise Handling | .then() , .catch() | Handle asynchronous operations: asyncFunc().then().catch(); |
Async/Await | async function() { await promise; } | Simplifies promise handling. Example: const data = await fetch(); |
Cluster Module | require('cluster'); | Use for load balancing: if (cluster.isMaster) { cluster.fork(); } |
Corollary
Node.js is a cornerstone for modern server-side development, offering unparalleled speed and scalability. This cheat sheet equips you with the essential tools, modules, and syntax to accelerate your Node.js journey. Whether you’re building REST APIs, handling real-time applications, or managing server tasks, this guide is your quick reference for mastering Node.js.
Bookmark this cheat sheet for your next project and level up your Node.js skills!
FAQs
What is Node.js used for?
Node.js is a runtime environment that allows you to execute JavaScript on the server side. It is commonly used for:
–Building RESTful APIs
–Developing real-time applications (e.g., chat apps)
–Creating server-side rendered (SSR) applications
–Streaming data and handling asynchronous tasks
What makes Node.js faster than traditional server-side technologies?
Node.js uses the V8 JavaScript engine and operates on a non-blocking, event-driven architecture, which allows it to handle multiple requests concurrently without waiting for I/O operations to complete.
How does Node.js handle asynchronous programming?
Node.js handles asynchronous programming using:
—Callbacks: Functions passed as arguments to execute after a task.
—Promises: Represent the eventual completion (or failure) of an asynchronous operation.
—Async/Await: Cleaner syntax to handle asynchronous code.
What are the key differences between require
and import
in Node.js?
—require
is used in CommonJS modules (default in Node.js).
—import
is used in ECMAScript modules (ESM) and requires "type": "module"
in package.json
.
—require
is synchronous, while import
is asynchronous.
How do I handle errors in Node.js?
Use a combination of:
Try-Catch blocks: For synchronous and async/await
operations.
Error callbacks: For functions using callbacks.
Global error handlers: Use process.on('uncaughtException', handler)
for unhandled exceptions.
What is the difference between process.nextTick
and setImmediate
?
process.nextTick
schedules a callback to execute before the next event loop iteration.setImmediate
schedules a callback to execute after the current event loop phase.
How do I handle environment variables in Node.js?
Use the process.env
object to access environment variables.
Store variables in a .env
file and use the dotenv
package to load them into process.env
.
How do I scale a Node.js application?
Clustering: Use the cluster
module to run multiple instances of your app across CPU cores.
Load Balancers: Distribute traffic among server instances using tools like NGINX.
Microservices Architecture: Break your application into smaller, independent services.
What is the best way to manage dependencies in Node.js?
Use package.json
to list dependencies.
Use npm install
or yarn
to manage libraries.
Regularly update dependencies with npm outdated
and audit vulnerabilities with npm audit
.
How do I secure a Node.js application?
Use Helmet to set secure HTTP headers.
Sanitize user inputs to prevent injection attacks.
Use bcrypt for password hashing.
Implement rate limiting with tools like express-rate-limit
.
Regularly scan for vulnerabilities with npm audit
.
How do I debug Node.js applications?
Use the Node.js Debugger with node inspect app.js
.
Use debugging tools like Chrome DevTools or VS Code debugger.
Add console.log()
for quick debugging (although not recommended for production).
What are some common performance issues in Node.js applications?
Blocking the event loop: Avoid long-running synchronous tasks.
Memory leaks: Use tools like heapdump or node-inspect to detect leaks.
Improper database queries: Optimize queries and use connection pooling.
Poor use of streams: Use Node.js streams effectively for large data handling.
What is the difference between npm
and npx
?
npm
: Node Package Manager used to install and manage packages.npx
: Executes Node.js packages directly without installing them globally.
How do I handle file uploads in Node.js?
Use middleware like Multer for parsing multipart/form-data
.
Example:
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), (req, res) => res.send('File uploaded!'));
Can I use TypeScript with Node.js?
Yes, install TypeScript and its type definitions for Node.js:
npm install typescript @types/node
Create a tsconfig.json
file and compile TypeScript files to JavaScript using tsc
.
What are the common Node.js frameworks?
Express.js: Lightweight, flexible, and popular.
Koa: Minimalist framework created by the same team as Express.
NestJS: Built with TypeScript, ideal for scalable server-side apps.
Hapi: Rich plugin architecture for building robust APIs.
How do I handle CORS in Node.js?
Use the cors
package:
const cors = require('cors');
app.use(cors());
How do I test Node.js applications?
Mocha and Chai for unit testing.
Jest for an all-in-one testing solution.
Mock APIs and services with Sinon.js or nock.
How can I use WebSockets in Node.js?
Use the ws
package to handle WebSocket connections:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => ws.send('Hello Client'));
What tools can I use for monitoring Node.js applications?
PM2: Process manager for Node.js apps.
New Relic or AppDynamics: For performance monitoring.
Log management tools: Use Winston or Bunyan for logging.
informative table , i will bookmark it.
Needed today , THanks