Skip to content

Instantly share code, notes, and snippets.

@incheon-kim
Last active March 27, 2020 08:49
Show Gist options
  • Save incheon-kim/f8f9f09b424b513d0a4244d5819e2cf6 to your computer and use it in GitHub Desktop.
Save incheon-kim/f8f9f09b424b513d0a4244d5819e2cf6 to your computer and use it in GitHub Desktop.
How to do GET request synchronously in node.js (http/https)
const https = require("https")
const httpsGetSync = (url) => {
return new Promise((resolve, reject) => {
let req = https.get(url, (res)=>{
var retData = "";
res.on("data", (chunk)=>{
// do your work here.
retData += chunk;
});
res.on("end", ()=>{
// resolve(return) data here.
resolve(retData);
});
});
req.on("error", (err)=>{
// throw err
reject(err);
});
req.end();
});
};
// example
var exampleFunc = async () => {
try{
var res = await httpsGetSync("www.example.com");
// do work with result
console.log(res);
} catch(err){
// catch error while request
console.error(err);
}
};
// or
var exampleFunc2 = () => {
httpsGetSync("www.example.com")
.then((res)=> {
// do work with result
console.log(res);
})
.catch((err)=>{
// catch error while request
console.err(err);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment