-
-
Save vdeturckheim/5d96705298a55a90a25716314edd449e to your computer and use it in GitHub Desktop.
This file contains 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
require('continuation-local-storage'); | |
const http = require('http'); | |
http.get('http://nodejs.org/dist/index.json', (res) => { | |
const statusCode = res.statusCode; | |
const contentType = res.headers['content-type']; | |
let error; | |
if (statusCode !== 200) { | |
error = new Error(`Request Failed.\n` + | |
`Status Code: ${statusCode}`); | |
} else if (!/^application\/json/.test(contentType)) { | |
error = new Error(`Invalid content-type.\n` + | |
`Expected application/json but received ${contentType}`); | |
} | |
if (error) { | |
console.log(error.message); | |
// consume response data to free up memory | |
res.resume(); | |
return; | |
} | |
res.setEncoding('utf8'); | |
let rawData = ''; | |
res.on('data', (chunk) => rawData += chunk); | |
res.on('end', () => { | |
try { | |
let parsedData = JSON.parse(rawData); | |
console.log(parsedData); | |
} catch (e) { | |
console.log(e.message); | |
} | |
}); | |
}).on('error', (e) => { | |
console.log(`Got error: ${e.message}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment