Skip to content

Instantly share code, notes, and snippets.

@monjer
Last active September 14, 2023 01:50
Show Gist options
  • Save monjer/ffad2b1994933c59e1d8f0d2afd6224f to your computer and use it in GitHub Desktop.
Save monjer/ffad2b1994933c59e1d8f0d2afd6224f to your computer and use it in GitHub Desktop.
Download file
import http from 'http';
import https from 'https';
import fs from 'fs';
export default async (url, dest) => {
const protocol = url.indexOf('https') === 0 ? https : http;
const fileStream = fs.createWriteStream(dest);
return new Promise((resovle, reject) => {
// http.IncomingMessage
const request = protocol.get(url, (response) => {
if (response.statusCode !== 200) {
reject(new Error(`Download failed, code ${response.statusCode}`))
}
response.pipe(fileStream);
});
request.on('error', (error) => {
reject(new Error(`Download failed, error message : ${error.toString()}`))
});
// 无论是finish 还是 error fileStream都会自动close掉
fileStream.on('finish', resovle);
fileStream.on('error', (error) => {
reject(new Error(`Write file failed, error message : ${error.toString()}`))
});
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment