Last active
January 27, 2022 01:20
-
-
Save Ragnoroct/02cd19c5ccf8e6c9967b33823ea3652d to your computer and use it in GitHub Desktop.
network-requests-standard-lib
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
const https = require("https") | |
const http = require("http") | |
(async () => { | |
await httpsGetToFile("https://example.com/", "/tmp/example.com.txt", { headers: {"Range": "bytes=0-4"}}) | |
})() | |
/** | |
* @param {string} uri | |
* @param {ClientRequestArgs} options | |
* @param {string} outFilePath | |
* @return {Promise<>} | |
* | |
* @see {@link https://nodejs.org/en/knowledge/HTTP/clients/how-to-create-a-HTTP-request/} | |
*/ | |
async function httpsGetToFile(uri, outFilePath, options = {}) { | |
return new Promise((resolve, reject) => { | |
const uriParsed = new URL(uri) | |
const httpModule = uriParsed.protocol === "https:" ? https : http | |
httpModule.request({ | |
...{ | |
protocol: uriParsed.protocol, | |
host: uriParsed.host, | |
path: uriParsed.pathname, | |
}, | |
...options | |
}, (response) => { | |
const writeStream = fs.createWriteStream(outFilePath) | |
writeStream.on("close", resolve) | |
response.pipe(writeStream) | |
response.on("error", reject) | |
}).end() | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment