50 Most Useful Node.js Snippets

Startup & Basics

1. Basic HTTP Server

const http = require('http');
http.createServer((req, res) => {
  res.write('Hello, Node.js!');
  res.end();
}).listen(3000, () => console.log('Server running on port 3000'));

2. Express Server Boilerplate

const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello Express'));
app.listen(3000, () => console.log('Express running'));

3. Serve Static Files with Express

app.use(express.static('public'));

4. CORS Setup

const cors = require('cors');
app.use(cors());

5. Parse Command-line Arguments

const args = process.argv.slice(2);
console.log(args);

File System

6. Read a File (Async)

const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

7. Write a File (Async)

fs.writeFile('output.txt', 'Hello!', err => {
  if (err) throw err;
});

8. Append to a File

fs.appendFile('output.txt', 'nAppend this!', err => {
  if (err) throw err;
});

9. Delete a File

fs.unlink('output.txt', err => {
  if (err) throw err;
});

10. Read Directory

fs.readdir('./', (err, files) => {
  if (err) throw err;
  console.log(files);
});

HTTP & API

11. Fetch with node-fetch

const fetch = require('node-fetch');
fetch('https://api.example.com/data')
  .then(res => res.json())
  .then(data => console.log(data));

12. Axios GET Request

const axios = require('axios');
axios.get('https://api.example.com/users')
  .then(res => console.log(res.data));

13. REST API with Express

app.get('/api/items', (req, res) => { res.json([{ name: 'item1' }]); });

14. Express Route Params

app.get('/user/:id', (req, res) => {
  res.send(req.params.id);
});

15. Express Error Handler

app.use((err, req, res, next) => {
  res.status(500).send('Something broke!');
});

Middleware & Logging

16. Morgan HTTP Logger

const morgan = require('morgan');
app.use(morgan('dev'));

17. Custom Logger Middleware

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

18. Helmet Security Middlewares

const helmet = require('helmet');
app.use(helmet());

19. Body Parser (Built-in in Express v4.16+)

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

20. Setting a Custom Header

app.use((req, res, next) => {
  res.setHeader('X-Powered-By', 'Node.js');
  next();
});

Authentication & Security

21. Bcrypt for Password Hashing

const bcrypt = require('bcrypt');
const hash = await bcrypt.hash('mypassword', 10);

22. JWT Token Generation

const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 1 }, 'yoursecret');

23. Validate JWT Middleware

app.use((req, res, next) => {
  const token = req.headers.authorization;
  try {
    jwt.verify(token, 'yoursecret');
    next();
  } catch (err) {
    res.status(401).send('Unauthorized');
  }
});

24. Rate Limiting

const rateLimit = require('express-rate-limit');
app.use(rateLimit({ windowMs: 60*1000, max: 100 }));

25. XSS Protection

const xss = require('xss-clean');
app.use(xss());

Database Snippets (MongoDB & SQL)

26. MongoDB Connection with Mongoose

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb')
  .then(() => console.log('Mongo connected'));

27. Create Mongoose Model

const User = mongoose.model('User', { name: String, age: Number });

28. Find in Mongoose

User.find({ age: { $gte: 18 } }).then(users => console.log(users));

29. Insert in Mongoose

const user = new User({ name: 'John', age: 30 });
user.save();

30. PostgreSQL Query (pg module)

const { Client } = require('pg');
const client = new Client();
await client.connect();
const res = await client.query('SELECT NOW()');

Modern Node.js Features

31. ES Modules

// package.json: { "type": "module" }
import fs from 'fs';

32. Top-level Await

// Top-level await is allowed in ESM
const res = await fetch('https://api.example.com');
console.log(await res.json());

33. Optional Chaining

const name = user?.profile?.name;

34. Nullish Coalescing

const port = process.env.PORT ?? 3000;

35. Async/Await with Try-Catch

try {
  const data = await axios.get('/api');
} catch(e) {
  console.error(e);
}

Real-Time & WebSocket

36. Simple WebSocket Server

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => ws.send('Hello client!'));

37. Real-time Events with Socket.IO

const io = require('socket.io')(3001);
io.on('connection', socket => {
  socket.emit('welcome', 'Connected!');
});

Utility & Useful Patterns

38. Debounce Utility

function debounce(fn, ms) {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn.apply(this, args), ms);
  };
}

39. Generate UUID

const { v4: uuidv4 } = require('uuid');
const id = uuidv4();

40. Read Environment Variables

require('dotenv').config();
console.log(process.env.MY_SECRET);

41. Global Error Handling

process.on('uncaughtException', err => {
  console.error(err);
  process.exit(1);
});

42. Sleep Utility

const sleep = ms => new Promise(res => setTimeout(res, ms));

Stream & Buffer

43. Read Stream

const stream = fs.createReadStream('file.txt');
stream.on('data', chunk => { console.log(chunk.toString()); });

44. Buffer from String

const buffer = Buffer.from('hello');

45. Pipe Streams

fs.createReadStream('input.txt').pipe(fs.createWriteStream('output.txt'));

Deployment & Production

46. Cluster Module for Multi-core

const cluster = require('cluster');
if (cluster.isMaster) {
  for (let i = 0; i < 3; i++) cluster.fork();
} else {
  // Worker process code
}

47. Graceful Shutdown

process.on('SIGTERM', () => {
  server.close(() => process.exit(0));
});

48. Serving a PDF File

app.get('/pdf', (req, res) => {
  res.contentType('application/pdf');
  fs.createReadStream('file.pdf').pipe(res);
});

Testing

49. Simple Mocha Test

const assert = require('assert');
describe('Math', () => {
  it('adds numbers', () => {
    assert.strictEqual(1 + 1, 2);
  });
});

50. Mock with Jest

jest.mock('./db');

Similar Posts