Last active
September 14, 2023 01:50
-
-
Save monjer/ffad2b1994933c59e1d8f0d2afd6224f to your computer and use it in GitHub Desktop.
Download file
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 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
How to download a file with Node.js (without using third-party libraries)?