javascript

More Advanced Node.js Code Snippets

Additional unique and advanced Node.js problem-solving code snippets.

Tarun Sharma
Tarun SharmaAugust 29, 2022 · 2 min read · Last Updated:

6. Throttle Function (Control Function Call Rate)

function throttle(fn, wait) {
  let lastTime = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastTime >= wait) {
      lastTime = now;
      fn.apply(this, args);
    }
  };
}

// Usage
const throttledLog = throttle(console.log, 2000);
throttledLog('This will log immediately');
throttledLog('This will be ignored if called within 2 seconds');

7. Recursive Directory Traversal (Async, Promises)

const fs = require('fs').promises;
const path = require('path');

async function walkDir(dir, fileList = []) {
  const files = await fs.readdir(dir);
  for (const file of files) {
    const filePath = path.join(dir, file);
    const stat = await fs.stat(filePath);
    if (stat.isDirectory()) {
      await walkDir(filePath, fileList);
    } else {
      fileList.push(filePath);
    }
  }
  return fileList;
}

// Usage
// walkDir('./some-directory').then(console.log);

8. Simple Event Emitter Implementation

class SimpleEventEmitter {
  constructor() {
    this.events = {};
  }
  on(event, listener) {
    (this.events[event] = this.events[event] || []).push(listener);
  }
  emit(event, ...args) {
    (this.events[event] || []).forEach((listener) => listener(...args));
  }
  off(event, listener) {
    if (!this.events[event]) return;
    this.events[event] = this.events[event].filter((l) => l !== listener);
  }
}

// Usage
// const emitter = new SimpleEventEmitter();
// emitter.on('data', (msg) => console.log(msg));
// emitter.emit('data', 'Hello!');

9. Timeout a Promise

function promiseTimeout(promise, ms) {
  let timeout = new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), ms));
  return Promise.race([promise, timeout]);
}

// Usage
// promiseTimeout(fetch('https://example.com'), 1000).catch(console.error);

10. Stream File Line by Line (No External Libraries)

const fs = require('fs');
const readline = require('readline');

function readLines(filePath, onLine) {
  const rl = readline.createInterface({
    input: fs.createReadStream(filePath),
    crlfDelay: Infinity,
  });
  rl.on('line', onLine);
  rl.on('close', () => console.log('Done reading file.'));
}

// Usage
// readLines('./file.txt', line => console.log('Line:', line));

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Tarun Sharma

Written byTarun Sharma
Tarun Sharma is a software engineer by day and a full-stack developer by night. He's coding for almost a decade now. He codes 🧑‍💻, write ✍️, learn 📖 and advocate 👍.
Connect

Is this page helpful?

Related VideosView All

Stack Overflow Clone - APIs Integration Redux Toolkit [Closure] - App Demo #05

Become Ninja Developer - API security Best Practices with Node JS Packages #15

Nest JS Microservices using HTTP Gateway and Redis Services (DEMO) #nestjs #microservices #16