Created
July 7, 2022 06:31
-
-
Save monjer/f91a40102f58c7fce8c552bbc50cae81 to your computer and use it in GitHub Desktop.
get file or remote file md5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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