将流写入字符串并从函数返回

时间:2017-05-13 07:22:40

标签: node.js

作为我正在编写的程序的一部分,我希望有一个辅助函数来缩短创建的一些长URL。我找到了package: 并且我试图更改代码,以便它只是将字符串存储在变量中并返回它。我在范围方面遇到了一些问题。变量resData从未实际更新,返回始终为空字符串。如何将此返回的字符串放入全局变量并返回?感谢

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

2 个答案:

答案 0 :(得分:1)

尝试使用回调函数

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

答案 1 :(得分:1)

这样做

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