Skip to content

Instantly share code, notes, and snippets.

@pbatey
Last active July 8, 2020 03:01
Show Gist options
  • Save pbatey/05b5670302f5435f0d7244b641ecc1aa to your computer and use it in GitHub Desktop.
Save pbatey/05b5670302f5435f0d7244b641ecc1aa to your computer and use it in GitHub Desktop.
Simple node function to get a url
const http = require('http')
const https = require('https')
async function fetch(url, options={rejectUnauthorized: false}, timeout=3000, log=true) {
await new Promise((resolve, reject) => {
const req = (/^https/.test(url) ? https : http)
.get(url, options, res => {
let data = ''
res.on('data', chunk => data+=chunk)
res.on('end', () => {log && console.log(data); resolve(data)})
res.on('error', err => {log && console.error(err); reject(err)})
})
.on('error', err => {log && console.error(err); reject(err)})
setTimeout(() => req.abort(), timeout) // socket hang up
})
}
@pbatey
Copy link
Author

pbatey commented Jul 8, 2020

The default options are insecure! - but useful for self-signed certs. Call fetch(url, {}) to validate https certificates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment