Created
September 13, 2024 14:05
-
-
Save mkgin/ceffab57f5c567c46629d4bf679c1d10 to your computer and use it in GitHub Desktop.
Using a Promise to return http.get response data
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
/* | |
* Returning the "data" part of a http response | |
* with Node.js using "Promise" | |
* | |
* Based on example code in the Node.js Documentation: | |
* https://nodejs.org/api/http.html#httpgetoptions-callback | |
*/ | |
const http = require('node:http'); | |
// Promise producer | |
let getHttpData = new Promise( function(getItDone, getItFailed) | |
{ | |
const req = http.get('http://localhost:8000/', (res) => { | |
const { statusCode } = res; | |
const contentType = res.headers['content-type']; | |
let error; | |
// Any 2xx status code signals a successful response but | |
// here we're only checking for 200. | |
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(); | |
getItFailed( "FAIL 1" ); | |
} | |
res.setEncoding('utf8'); | |
let rawData = ''; | |
res.on('data', (chunk) => { rawData += chunk; }); | |
res.on('end', () => { | |
try { | |
const parsedData = JSON.parse(rawData); | |
console.log('LOG parsedData.data: ', | |
parsedData.data ); | |
outputData = parsedData.data; | |
getItDone( outputData ) ; | |
} catch (e) { | |
console.error(e.message); | |
getItFailed( "FAIL 2" ); | |
} | |
}); | |
}).on('error', (e) => { | |
console.error(`Got error: ${e.message}`); | |
getItFailed( "FAIL 3" ); | |
}); | |
console.log('LOG : Made it to the end'); | |
}); | |
// Create a local server to receive data from | |
const server = http.createServer((req, res) => { | |
res.writeHead(200, { 'Content-Type': 'application/json' }); | |
res.end(JSON.stringify({ | |
data: 'Hello World!', | |
})); | |
}); | |
// Start local server on port 8000 | |
server.listen(8000); | |
// Promise consumer | |
getHttpData.then( | |
function(value) { | |
console.log('*** SUCCESS ***\n' | |
, value , | |
'\n*** SUCCESS ***'); | |
}, | |
function(error) { | |
console.log('*** FAIL ***\n', | |
error, | |
'\n*** FAIL ***');} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment