Node.js Snippets

Reusable backend code snippets using Node.js.

export function formatFileSize(bytes: number): string {
  if (typeof bytes !== 'number' || isNaN(bytes) || bytes < 0) {
    return 'Invalid size';
  }

  const units = ['bytes', 'KB', 'MB', 'GB', 'TB'];
  let i = 0;

  while (bytes >= 1024 && i < units.length - 1) {
    bytes /= 1024;
    i++;
  }

  const value = i === 0 ? bytes : bytes.toFixed(2);
  return `${value} ${units[i]}`;
}


// Example usage:
console.log(formatFileSize(500));           // 500 B
console.log(formatFileSize(1536));          // 1.50 KB
console.log(formatFileSize(1048576));       // 1.00 MB
console.log(formatFileSize(1073741824));    // 1.00 GB
console.log(formatFileSize());    // "Invalid size"

File size bytes to a human-readable format

Common Conversions (Binary - Base 2) – m...
function sanitizeFilename(filename) {
  // Remove the extension
  const nameWithoutExt = filename.replace(/\.[^/.]+$/, '')

  // Replace all non-alphanumeric characters with hyphens
  const sanitized = nameWithoutExt.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '')

  return sanitized
}

// Example usage
const input = "Mahbub-hasan.Hira.jpg";
const result = sanitizeFilename(input);
console.log(result); // Output: Mahbub-hasan-Hira

Get the filename without extension

1. firstly we remove the extension by r...
const generateUsername = email =>
  email.split('@')[0].replace(/[^a-zA-Z0-9]/g, '') + '_' + Math.random().toString(36).slice(2, 6);

// Example
console.log(generateUsername('john.doe@example.com')); // output ==>  johndoe_ab3x

Generate a unique username from email

How it works: 1. split('@')[0]: takes th...