Created
November 15, 2019 12:18
-
-
Save Avaray/1a9037163e074853f7e1a265ace3e608 to your computer and use it in GitHub Desktop.
[NodeJS] HTTP Request without dependencies // https://www.tomas-dvorak.cz/posts/nodejs-request-without-dependencies/
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
| const request = function(url) { | |
| return new Promise((resolve, reject) => { | |
| const lib = url.startsWith('https') ? require('https') : require('http'); | |
| const request = lib.get(url, (response) => { | |
| if (response.statusCode < 200 || response.statusCode > 299) { | |
| reject(new Error('Failed to load page, status code: ' + response.statusCode)); | |
| } | |
| const body = []; | |
| response.on('data', (chunk) => body.push(chunk)); | |
| response.on('end', () => resolve(body.join(''))); | |
| }); | |
| request.on('error', (err) => reject(err)) | |
| }) | |
| }; | |
| request('https://news.ycombinator.com/') | |
| .then((html) => console.log(html)) | |
| .catch((err) => console.error(err)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment