stream+pipe의md5를 이용한 계산

6025 단어 JavaScriptNode.jstech
stream을 사용하여 http를 통해 이미지 데이터를 읽고 클라우드 메모리 장치에 기록하는 처리를 실현했습니다.
그림의md5가 필요하기 때문에stream의pipe를 이용하여 잘할 수 있는지 조사했습니다.

해결작


hash용 데이터만 추출하고 실제 데이터는 가공되지 않은 상태에서 하류로 흘러가며Transform류를 실현한다.

샘플 코드


로컬 파일의stream 읽기, 쓰기 예입니다.
도중에 MD5 계산용 Transform을 물고
stream.js
const fs = require('fs');
const crypto = require('crypto');
const { Transform } = require('stream');

const src = fs.createReadStream('small.jpg');
const dest = fs.createWriteStream('small_dest.jpg');

//Streamデータを抜き取りmd5を計算する処理
const hash = crypto.createHash('md5');
const hashTransform = new Transform({
  transform(
    chunk,
    encoding,
    done
  ) {
    hash.update(chunk); // hash用にデータだけ抜き取る
    this.push(chunk) // データを下流のパイプに渡す処理
    done() // 変形処理終了を伝えるために呼び出す
  },
});

//メイン処理
src.pipe(hashTransform).pipe(dest).on('finish', () => {
  const md5sum = hash.digest('hex');
  console.log(md5sum);
});

실행 결과


~/w/s/stream ❯❯❯ node ./stream.js
285903447e55e04bc21068a1f263768d
~/w/s/stream ❯❯❯ md5sum small.jpg
285903447e55e04bc21068a1f263768d  small.jpg
순조롭게 진행되다🤗

참고 자료


https://nodejs.org/api/crypto.html#crypto_class_hash
https://qiita.com/masakura/items/5683e8e3e655bfda6756

좋은 웹페이지 즐겨찾기