Created
November 24, 2012 09:48
-
-
Save sunny0425/4139064 to your computer and use it in GitHub Desktop.
七天七语言--node.js篇 作业(http://be001.com/jams/445)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 测试: | |
// http://localhost:8888/?short_url=http://t.cn/zjUg9kQ(正确解析) | |
// http://localhost:8888/?short_url=http://t.cn/zj4SIjW (有https请求,会报错) | |
var http = require('http'); | |
var url = require('url'); | |
function myParse(short_url, callback){ | |
var result = ''; | |
try{ | |
req = http.get(short_url, function(res) { | |
if(res.statusCode == '302'){ | |
myParse(res.headers.location, callback); | |
} | |
else{ | |
res.setEncoding('utf8'); | |
res.on('data', function (chunk) { | |
var m = chunk.match(/<title>(.+)<\/title>/); | |
if(m) { | |
result = "{ url: \"" + short_url + "\", title: \"" + m[1] + "\"}"; | |
console.log(result); | |
callback(null, result); | |
} | |
else{ | |
callback(null, ''); | |
} | |
}) | |
} | |
}).on('', function(e){ | |
console.log("request error: " + e.message); | |
}); | |
} | |
catch(error){ | |
console.log(error.message); | |
} | |
} | |
http.createServer(function(request, response) { | |
var q = url.parse(request.url, true); | |
var short_url; | |
if(q.query && q.query.short_url){ | |
short_url = q.query.short_url; | |
myParse(short_url, function(err, result){ | |
if(result.length){ | |
response.write(result); | |
response.end(); | |
} | |
}); | |
} | |
}).listen(8888); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment