Generate a unique character string suitable for use in files and URLs.
npx @tessl/cli install tessl/npm-unique-slug@5.0.0unique-slug generates unique 8-character hexadecimal strings suitable for use in filenames and URLs. It offers two modes of operation: random generation using Math.random() for unpredictable identifiers, and deterministic generation using MurmurHash3 algorithm for consistent hashes from input strings.
npm install unique-slugvar uniqueSlug = require('unique-slug');For ES modules:
import uniqueSlug from 'unique-slug';var uniqueSlug = require('unique-slug');
// Generate random slug
var randomSlug = uniqueSlug();
console.log(randomSlug); // e.g., "a1b2c3d4"
// Generate deterministic slug from string
var fileSlug = uniqueSlug('/etc/passwd');
console.log(fileSlug); // Always produces same output for same inputGenerates a unique 8-character hexadecimal string using either random generation or deterministic hashing.
/**
* Generate a unique character string suitable for use in files and URLs
* @param {string} [uniq] - Optional string to hash deterministically
* @returns {string} 8-character hexadecimal string
*/
function uniqueSlug(uniq);Parameters:
uniq (optional): String - If provided, generates a deterministic hash using MurmurHash3. If omitted, generates a random 8-character hex string.Returns:
string: Always returns exactly 8 hexadecimal characters (0-9, a-f)Behavior:
uniq parameter: Uses MurmurHash3 to create a consistent hash from the input string, padded with leading zeros to ensure 8 charactersuniq parameter: Uses Math.random() to generate random bytes, converted to hexadecimal and padded to 8 charactersUsage Examples:
var uniqueSlug = require('unique-slug');
// Random generation - different each time
var slug1 = uniqueSlug();
var slug2 = uniqueSlug();
console.log(slug1); // e.g., "7f3a9b2c"
console.log(slug2); // e.g., "d4e5f6a7"
// Deterministic generation - same input produces same output
var pathSlug1 = uniqueSlug('/path/to/file');
var pathSlug2 = uniqueSlug('/path/to/file');
console.log(pathSlug1); // e.g., "1a2b3c4d"
console.log(pathSlug2); // e.g., "1a2b3c4d" (identical)
// Different inputs produce different outputs
var slug3 = uniqueSlug('/different/path');
console.log(slug3); // e.g., "9e8d7c6b" (different from pathSlug1)
// Common use cases
var tempFile = '/tmp/cache-' + uniqueSlug() + '.json';
var consistentId = uniqueSlug(userEmail + timestamp);Common Use Cases: