1

hi i am trying to short my urls

function shorutrl(link)
{
var linkpost = JSON.stringify({longUrl:link});.

        var optionslink = {
        host: "www.googleapis.com",
        port: 443,
        method: 'POST',
        path: "/urlshortener/v1/url",
        headers: {
        'Content-Type' : 'application/json'
        }
    };

optionslink.headers['Content-Length']=linkpost.length;
var linkreq = https.request(optionsimg, function(res) {
                res.on('data', function (d) {
                linkdata+=d;
                });
                res.on('end', function (x) {
                try { return JSON.parse(linkdata).id; } catch(e){ return link; }
                });
            }).on('error', function (e) {
                //console.log(e.message);
            });
linkreq.write(optionslink);
linkreq.end();
}

function nonworking_givelink()
{
   return shorutrl(txtlinks[Math.floor(Math.random() * txtlinks.length)]);
}

function working_givelink()
{
   return txtlinks[Math.floor(Math.random() * txtlinks.length)];
}

nonworking_givelink returns undefined working_givelink returns link as normal

should i write a new function and pass paramters to that and generate new link and pass the paramters to another function is there no any easier way?

1
  • Where is working_givelink? Commented Dec 10, 2012 at 15:37

2 Answers 2

3

You shouldn't write blocking code in node.js, it goes against the very design of the system.

You need to pass a callback function which will be called with the new URL within your .on('end', ...) block.

Alternatively, wrap this up into a new object which itself emits events, e.g.:

var https = require('https');
var events = require('events');

function GoogleShortener() {
    events.EventEmitter.call(this);
};

GoogleShortener.super_ = events.EventEmitter;
GoogleShortener.prototype = Object.create(events.EventEmitter.prototype, {
    constructor: {
        value: GoogleShortener,
        enumerable: false
    }
});

GoogleShortener.prototype.shorten = function(link) {

    var self = this;
    var data = JSON.stringify({longUrl: link});

    var options = {
        hostname: 'www.googleapis.com',
        port: 443,
        path: '/urlshortener/v1/url',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': data.length
        }
    };

    var resp = '';

    var req = https.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function(d) {
            resp += d;
        }).on('end', function() {
            try {
                var id = JSON.parse(resp).id;
                self.emit('success', id);
            } catch (e) {
                self.emit('error', e);
            }
        });
    }).on('error', function(e) {
        self.emit('error', e);
    });

    req.write(data);
    req.end();

    return self;
};

exports.shorten = function(link) {
    return new GoogleShortener().shorten(link);
};

usage:

var g = require('gshort');
g.shorten('http://www.google.com/').on('success', function(link) {
     console.log(link)
});
Sign up to request clarification or add additional context in comments.

3 Comments

my parameters is more than 1 kb i already pass them to 3-4 for image link, description , text , and for link and i already use return at .on('end' event
the size of your paramaters is irrelevant, you simply can't write this function the way you have. You must arrange for an asynchronous function to be called once the final result is known.
so they must delete return function its not required while its not important what returns
0

return doesn't return from the function you want it to return from. It returns from the function immediately around it. Consider:

function foo() {
    var bar = function() {
        return "baz";  // This does _not_ return from `foo`! It returns from `bar`
    }
    bar();
}

console.log(foo())  // undefined

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.