Quantcast
Channel: Write a stream to a string and return it from a function - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Write a stream to a string and return it from a function

0
0

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: 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
}
};

Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images