Nodejs-Cheatsheet

👋 Hello World

// hello.js
console.log("Hello, World!");

💡 Tip: Run your script with node hello.js.

📦 Variables & Data Types

let age = 25;
const name = "Maxon";
let isAdmin = true;
let scores = [95, 88, 76];
let user = { name: "Maxon", age: 25 };

console.log(`${name} is ${age} years old.`);

💡 Tip: Use const for constants and let for reassignable variables. Avoid var.

🔀 Control Flow

for (let i = 1; i <= 5; i++) {
  if (i % 2 === 0) console.log(`${i} is Even`);
  else console.log(`${i} is Odd`);
}

💡 Tip: Try for...of and for...in loops for arrays and objects.

🛠 Functions

function add(a, b) {
  return a + b;
}

const multiply = (a, b) => a * b;

console.log("Sum:", add(5, 3));
console.log("Product:", multiply(4, 2));

💡 Tip: Use arrow functions for concise, modern syntax.

📦 Modules (Import/Export)

// math.js
export function add(a, b) {
  return a + b;
}

// main.js
import { add } from "./math.js";
console.log(add(10, 5));

💡 Tip: Use type="module" in package.json or file for ES Modules. Use require for CommonJS.

📂 File System

import fs from "fs";

fs.writeFileSync("data.txt", "Hello File!");
const content = fs.readFileSync("data.txt", "utf-8");
console.log(content);

💡 Tip: Use fs/promises for async file operations.

🌐 HTTP Server

import http from "http";

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello from Node.js Server!");
});

server.listen(3000, () => console.log("Server running on port 3000")); 

💡 Tip: Use nodemon to auto-restart the server during development.

⚡ Express.js

import express from "express";
const app = express();

app.get("/", (req, res) => res.send("Welcome to Express!"));

app.listen(3000, () => console.log("Server running at http://localhost:3000")); 

💡 Tip: Express simplifies routing, middleware, and APIs in Node.js.

⏳ Async / Await

const fetchData = async () => {
  const response = await fetch("https://api.github.com");
  const data = await response.json();
  console.log(data);
};

fetchData();

💡 Tip: Wrap await calls in try...catch for error handling.

🔗 Promises

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

delay(1000).then(() => console.log("1 second later..."));

💡 Tip: Promises help manage asynchronous operations cleanly.

🎧 Events

import { EventEmitter } from "events";
const emitter = new EventEmitter();

emitter.on("greet", name => console.log(`Hello, ${name}`));
emitter.emit("greet", "Maxon");

💡 Tip: The EventEmitter pattern powers Node’s async architecture.

💧 Streams

import fs from "fs";

const readStream = fs.createReadStream("data.txt");
readStream.on("data", chunk => console.log("Chunk:", chunk.toString()));

💡 Tip: Streams are great for handling large files efficiently.

📦 NPM & Packages

// Install a package
npm install express

// Uninstall
npm uninstall express

// Initialize project
npm init -y

💡 Tip: Use npx to run packages without global installs.

🗂 JSON Handling

const user = { name: "Alice", age: 30 };
const jsonStr = JSON.stringify(user);
const obj = JSON.parse(jsonStr);

console.log(jsonStr, obj);

💡 Tip: JSON is native in Node.js — use JSON.stringify() and JSON.parse().

⚠️ Error Handling

try {
  throw new Error("Something went wrong!");
} catch (err) {
  console.error("Error:", err.message);
}

💡 Tip: Always handle errors in async code with try...catch or .catch().

🌱 Environment Variables

// .env
PORT=4000

// app.js
import dotenv from "dotenv";
dotenv.config();
console.log(process.env.PORT);

💡 Tip: Store secrets in .env and never commit them.

🔍 Debugging

console.log("Debug Info:", data);
console.error("Error:", err);
debugger; // triggers breakpoint

💡 Tip: Use node --inspect and Chrome DevTools for debugging.

Post a Comment