Node.jsではmd5の変換は標準関数では用意されていないので手組みするか、npmパッケージを使うかになります。
const crypto = require('crypto') function md5hex(str /*: string */) { const md5 = crypto.createHash('md5') return md5.update(str, 'binary').digest('hex') }
npmパッケージは以下です。
リポジトリのソースを見ると複雑です。
パフォーマンスが高めるためなのかな、と思いました。
計測してみます。
const md5 = require('md5'); const Benchmark = require('benchmark'); const suite = new Benchmark.Suite; const crypto = require('crypto') function md5hex(str /*: string */) { const md5 = crypto.createHash('md5') return md5.update(str, 'binary').digest('hex') } var text = "Hello World!" console.log(md5(text)); console.log(md5hex(text)); // add tests suite .add('package', function () { md5(text); }) .add('handmade', function () { md5hex(text); }) // add listeners .on('cycle', function (event) { console.log(String(event.target)); }) .on('complete', function () { console.log('Fastest is ' + this.filter('fastest').map('name')); }) // run async .run({'async': true});
なんと意外、手組みの方が速いです。
ed076287532e86365e841e92bfc50d8c ed076287532e86365e841e92bfc50d8c package x 253,219 ops/sec ±5.81% (84 runs sampled) handmade x 379,276 ops/sec ±14.24% (60 runs sampled) Fastest is handmade
とはいえ、毎回手組みするのも面倒ですし、パッケージ使った方が楽かなと。
パッケージのリポジトリを見ると、Issueでは様々な指摘に対応しているので、そんな様々なケースに対応しているのでしょう。