Created
November 5, 2017 01:46
-
-
Save anyinan/113b8e99cbb3d1b2843b566aaeb2a762 to your computer and use it in GitHub Desktop.
useage of Node http.get()
This file contains hidden or 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
| 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