Node.js Cheatsheet
10xdev.blog/cheatsheets
# 1. NPM (Node Package Manager)
# Initialize a new project (creates package.json)
npm init -y

# Install a package and save it as a dependency
npm install express

# Install a package and save it as a dev dependency
npm install --save-dev nodemon

# Install all dependencies from package.json
npm install

# Uninstall a package
npm uninstall express

# Run a script defined in package.json
npm run dev
# 2. Modules (CommonJS & ES Modules)
// --- CommonJS (default in .js files) ---

// Exporting
// my-module.js
const myFunction = () => 'Hello';
module.exports = myFunction;

// Importing
// main.js
const myFunction = require('./my-module.js');
console.log(myFunction());


// --- ES Modules (in .mjs files or "type": "module" in package.json) ---

// Exporting
// my-module.mjs
export const myFunction = () => 'Hello';
export default () => 'Default Hello';

// Importing
// main.mjs
import myDefaultFunction, { myFunction } from './my-module.mjs';
console.log(myFunction());
console.log(myDefaultFunction());
# 3. File System (fs) Module
const fs = require('fs');
const fsPromises = require('fs').promises;

// Asynchronous Read (with callback)
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

// Synchronous Read (blocks execution)
try {
  const data = fs.readFileSync('example.txt', 'utf8');
  console.log(data);
} catch (err) {
  console.error(err);
}

// Promises-based Read (recommended)
async function readFileWithPromises() {
  try {
    const data = await fsPromises.readFile('example.txt', 'utf8');
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}
readFileWithPromises();
# 4. Path Module
const path = require('path');

// Join path segments together
const filePath = path.join(__dirname, 'public', 'index.html');
// Result on Linux/macOS: /path/to/project/public/index.html
// Result on Windows: C:\path\to\project\public\index.html

console.log(filePath);

// Get the base file name
console.log(path.basename(filePath)); // index.html

// Get the directory name
console.log(path.dirname(filePath)); // /path/to/project/public

// Get the extension
console.log(path.extname(filePath)); // .html
# 5. HTTP Server (Built-in)
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, World!\n');
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});
# 6. Express.js Framework
// A minimal Express server
const express = require('express');
const app = express();
const PORT = 3000;

// Middleware to parse JSON bodies
app.use(express.json());

// Basic GET route
app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

// Route with parameters
app.get('/users/:id', (req, res) => {
  res.send(`User ID: ${req.params.id}`);
});

// Basic POST route
app.post('/users', (req, res) => {
  const newUser = req.body;
  // Logic to create user...
  res.status(201).send(newUser);
});

app.listen(PORT, () => {
  console.log(`Express server listening on port ${PORT}`);
});
# 7. Event Emitter
const EventEmitter = require('events');

// Create a custom event emitter
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();

// Register a listener for the 'myEvent' event
myEmitter.on('myEvent', (arg) => {
  console.log('An event occurred!', arg);
});

// Emit the 'myEvent' event
myEmitter.emit('myEvent', { message: 'Hello Event' });
master* 0 0