Last active
March 27, 2020 08:49
-
-
Save incheon-kim/f8f9f09b424b513d0a4244d5819e2cf6 to your computer and use it in GitHub Desktop.
How to do GET request synchronously in node.js (http/https)
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 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