As part of a program I am writing, I'd like to have a helper function that shortens some long URLs that are created. I found this package: https://www.npmjs.com/package/tinyurl and am attempting to change the code so that it simply stores the string in a variable and returns it. I am having some issues with scope. the variable resData is never actually updated and return is always an empty string. How can I get this returned string into the global variable and return it? Thanks
var http = require("http")
module.exports = {
shorten: function(url) {
var resData = ''
http.get('[tinyurl api endpoint]' + encodeURIComponent(url), (res) => {
res.setEncoding('utf8')
res.on('data', (chunk) => {resData += chunk})
res.on('end', () => {
resData = resData.toString()
//this contains the link, and can be console.logged
})
}).on('error', (e) => {
console.log(e)
})
return resData //returns empty string
}
};
via Ross Cournoyer
No comments:
Post a Comment