Skip to content

Instantly share code, notes, and snippets.

@anyinan
Created November 5, 2017 01:46
Show Gist options
  • Select an option

  • Save anyinan/113b8e99cbb3d1b2843b566aaeb2a762 to your computer and use it in GitHub Desktop.

Select an option

Save anyinan/113b8e99cbb3d1b2843b566aaeb2a762 to your computer and use it in GitHub Desktop.
useage of Node http.get()
http.get('http://nodejs.org/dist/index.json', (res) => {
const { statusCode } = res;
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.error(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 {
const parsedData = JSON.parse(rawData);
console.log(parsedData);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment