Node.js Cheatsheet

1. Basic Setup and Global Objects

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

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

// Global objects
console.log(__dirname);  // Directory path
console.log(__filename);  // File path

2. Modules (CommonJS and ES Modules)

// Exporting a module (CommonJS)
module.exports = function greet() {
  console.log('Hello, Node.js!');
};

// Importing a module (CommonJS)
const greet = require('./greet');
greet();

// Exporting a module (ES Modules)
export const greet = () => console.log('Hello, ES Modules!');

// Importing a module (ES Modules)
import { greet } from './greet.js';
greet();

3. Asynchronous Programming (Callbacks, Promises, Async/Await)

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

// Promise example
const readFile = (fileName) => {
  return new Promise((resolve, reject) => {
    fs.readFile(fileName, 'utf8', (err, data) => {
      if (err) reject(err);
      else resolve(data);
    });
  });
};

readFile('file.txt').then(console.log).catch(console.error);

// Async/await example
const readFileAsync = async () => {
  try {
    const data = await readFile('file.txt');
    console.log(data);
  } catch (err) {
    console.error(err);
  }
};
readFileAsync();

4. File System (fs Module)

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

// Writing to a file
fs.writeFile('output.txt', 'Hello, world!', (err) => {
  if (err) throw err;
  console.log('File saved!');
});

// Sync version
const data = fs.readFileSync('file.txt', 'utf8');
console.log(data);

5. Streams and Buffers

// Streams
const fs = require('fs');
const readStream = fs.createReadStream('file.txt', { encoding: 'utf8' });

readStream.on('data', (chunk) => {
  console.log('Received:', chunk);
});

readStream.on('end', () => {
  console.log('End of file');
});

// Buffers
const buf = Buffer.from('Hello, world!', 'utf8');
console.log(buf.toString());  // Converts buffer back to string

6. Events and EventEmitters

// EventEmitter example
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();

// Listener
eventEmitter.on('greet', () => {
  console.log('Hello from event!');
});

// Emit event
eventEmitter.emit('greet');

7. HTTP Module (Creating a Basic Server)

// Simple HTTP server
const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  res.end('<h1>Hello, Node.js!</h1>');
});

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

8. Express.js (Routing, Middleware)

// Express.js basic setup
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello, Express.js!');
});

app.listen(3000, () => console.log('Server running on port 3000'));

// Middleware example
app.use((req, res, next) => {
  console.log('Middleware function');
  next();
});

9. Database Connections (MongoDB, MySQL)

// MongoDB (using Mongoose)
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true });

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

User.find({}, (err, users) => {
  if (err) throw err;
  console.log(users);
});

// MySQL
const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'test_db'
});

connection.connect();

connection.query('SELECT * FROM users', (err, results) => {
  if (err) throw err;
  console.log(results);
});

10. Working with JSON

// JSON parsing
const jsonString = '{ "name": "John", "age": 30 }';
const obj = JSON.parse(jsonString);
console.log(obj.name);  // Output: John

// JSON stringify
const newObj = { name: 'Jane', age: 25 };
const newJsonString = JSON.stringify(newObj);
console.log(newJsonString);

11. Error Handling (Try/Catch, Promises, Events)

// Try/Catch for synchronous code
try {
  throw new Error('Something went wrong!');
} catch (err) {
  console.error(err.message);
}

// Promise error handling
const promise = new Promise((resolve, reject) => {
  reject('Error in promise');
});

promise.catch(err => console.error(err));

// EventEmitter error handling
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('error', (err) => {
  console.error('Error event:', err);
});
emitter.emit('error', new Error('Oops!'));

12. Process Management (Child Processes, Clusters)

// Spawning a child process
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`Output: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.error(`Error: ${data}`);
});

ls.on('close', (code) => {
  console.log(`Child process exited with code ${code}`);
});

// Cluster module (scaling with multiple processes)
const cluster = require('cluster');
const http = require('http');

if (cluster.isMaster) {
  const cpuCount = require('os').cpus().length;
  for (let i = 0; i < cpuCount; i++) {
    cluster.fork();
  }
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('Hello from worker process!\n');
  }).listen(8000);
}

14. Testing (Mocha, Chai, Jest)

// Mocha + Chai
const chai = require('chai');
const expect = chai.expect;
describe('Array', () => {
  it('should start empty', () => {
    const arr = [];
    expect(arr).to.be.an('array').that.is.empty;
  });
});

// Jest example
test('adds 1 + 2 to equal 3', () => {
  expect(1 + 2).toBe(3);
});

15. Security Best Practices

// Helmet for securing HTTP headers
const helmet = require('helmet');
app.use(helmet());

// Rate limiting
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000,  // 15 minutes
  max: 100  // limit each IP to 100 requests per windowMs
});
app.use(limiter);