user2231715
user2231715

Reputation:

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

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

Upvotes: 0

Views: 163

Answers (2)

Kanad Chourasia
Kanad Chourasia

Reputation: 531

Try to use with callback function

shorten: function(url,callback) {

    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
            callback(null,resData); //<----here
        })
    }).on('error', (e) => {
        console.error(e);
        callback(e,null); //<----- and here
    })
}

Upvotes: 1

dev07
dev07

Reputation: 356

do this

    var http = require("http")

    module.exports = {
        shorten: function(url,cb) {

            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
                    cb(null,resData)  //<----- use callback (thanks robertklep)
                })
            }).on('error', (e) => {
                console.log(e)
            })

           //--> return resData //returns empty string as node is non-blocking io, this line will be executed before http response is received
      }
    };

//index.js

var http = require('./path/to/that/module')
http.shorten(url,function(error,result){ console.log(result) })

Upvotes: 1

Related Questions