Skip to content

Instantly share code, notes, and snippets.

@Ragnoroct
Last active January 27, 2022 01:20
Show Gist options
  • Save Ragnoroct/02cd19c5ccf8e6c9967b33823ea3652d to your computer and use it in GitHub Desktop.
Save Ragnoroct/02cd19c5ccf8e6c9967b33823ea3652d to your computer and use it in GitHub Desktop.
network-requests-standard-lib
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