Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8829

Node.js: ランダムな文字列を生成する1行の関数

$
0
0

Node.jsでランダムな文字列を生成する関数です。

  • lengthで与えた長さの文字列を生成します。
  • 生成される文字列は/[0-9a-z]*/です。
  • 用途としては、初期パスワードの生成や短縮URLのキーの生成など。
const{randomBytes}=require('crypto')functiongenerateRandomString(length){returnrandomBytes(length).reduce((p,n)=>p+n.toString(36).slice(-1),'')}

実行例

constassert=require('assert')constlengthList=[0,1,2,4,8,16]for(letlengthoflengthList){constrandomString=generateRandomString(length)console.log('string(%i) %o',randomString.length,randomString)assert(randomString.length===length)}

実行結果

string(0) ''
string(1) '3'
string(2) 'dy'
string(4) 'jk0g'
string(8) 'lvyzo8do'
string(16) '85hnhykoxwd2ofdd'

これよりも暗号学的に正しい実装があれば教えて下さい。


Viewing all articles
Browse latest Browse all 8829

Trending Articles