stream+pipe의md5를 이용한 계산
6025 단어 JavaScriptNode.jstech
그림의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
순조롭게 진행되다🤗참고 자료
Reference
이 문제에 관하여(stream+pipe의md5를 이용한 계산), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://zenn.dev/tyaahan/articles/b36cf74c971d29텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)