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