Sunday, February 05, 2023

node.js generate UUID + NanoID

no need to import uuid module; node.js embedded crypto can do the job

3 efficient ways to generate UUID in Node.js

import crypto from 'node:crypto'; console.log(crypto.randomUUID()); 00a6fa25-df29-4701-9077-557932591766


ai/nanoid: A tiny (130 bytes), secure, URL-friendly, unique string ID generator for JavaScript

A tiny, secure, URL-friendly, unique string ID generator for JavaScript.

“An amazing level of senseless perfectionism, which is simply impossible not to respect.”

  • Small. 130 bytes (minified and gzipped). No dependencies. Size Limit controls the size.
  • Safe. It uses hardware random generator. Can be used in clusters.
  • Short IDs. It uses a larger alphabet than UUID (A-Za-z0-9_-). So ID size was reduced from 36 to 21 symbols.
  • Portable. Nano ID was ported to 20 programming languages.
import { nanoid } from 'nanoid'
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"

{Blocks} in GoLang & Rust

 Using {Blocks} in Rust & Go for Fun & Profit

a substitute for "missing" try/catch in Go: { Blocks }
clever


id := 123 firstName := "John" lastName := "Smith" { result, err := db.Exec( `UPDATE usr SET first_name = $2 WHERE id = $1`, id, firstName, ) if result.RowsAffected() = 0 || err != nil { return err } } { result, err := db.Exec( `UPDATE usr SET last_name = $2 WHERE id = $1`, id, lastName, ) if result.RowsAffected() = 0 || err != nil { return err } }