Skip to content

Instantly share code, notes, and snippets.

@monjer
Created July 7, 2022 06:31
Show Gist options
  • Save monjer/f91a40102f58c7fce8c552bbc50cae81 to your computer and use it in GitHub Desktop.
Save monjer/f91a40102f58c7fce8c552bbc50cae81 to your computer and use it in GitHub Desktop.
get file or remote file md5
import crypto from 'crypto';
import fs from 'fs';
import http from 'http';
import https from 'https';
export const getFileMD5 = async (filePath, encoding='hex') => {
const hash = crypto.createHash('md5');
hash.setEncoding(encoding);
return new Promise((resolve, reject) => {
fs.createReadStream(filePath)
.once('error', reject)
.pipe(hash)
.once('finish', () => {
resolve(hash.read());
});
})
}
export const getRemoteFileMD5 = async (url, encoding='hex') => {
return new Promise((resolve, reject) => {
const isHttps = url.indexOf('https') === 0;
const protocol = isHttps ? https : http;
const hash = crypto.createHash('md5');
hash.setEncoding(encoding);
protocol.get(url, (response) => {
response.once('error', reject)
.pipe(hash)
.once('finish', () => {
resolve(hash.read());
})
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment