Skip to content

Instantly share code, notes, and snippets.

@vdeturckheim
Created May 16, 2017 13:14
Show Gist options
  • Save vdeturckheim/5d96705298a55a90a25716314edd449e to your computer and use it in GitHub Desktop.
Save vdeturckheim/5d96705298a55a90a25716314edd449e to your computer and use it in GitHub Desktop.
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