Skip to content

Instantly share code, notes, and snippets.

@RandomEtc
Created May 16, 2012 21:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RandomEtc/2714295 to your computer and use it in GitHub Desktop.
Save RandomEtc/2714295 to your computer and use it in GitHub Desktop.
Minimal node.js server to pass Twitter API responses through JSON parse and stringify
var http = require('http')
https = require('https'),
url = require('url');
// proxy json requests to Twitter API, round-trip through JSON.parse/stringify:
http.createServer(function (req, res) {
if (req.url.indexOf('.json') == req.url.length - '.json'.length) {
var options = { host: 'api.twitter.com', path: req.url }
https.get(options, function(got) {
console.log("Got response: " + got.statusCode);
var b = new Buffer(0);
res.writeHead(200, {'Content-Type': got.headers['content-type'] || 'application/json'});
got.on('data', function(d) {
b += d;
});
got.on('end', function() {
console.log('response ends');
var str = b.toString();
var data = JSON.parse(str);
res.end(JSON.stringify(data,false));
})
}).on('error', function(e) {
console.log("Got error: " + e.message);
res.write(JSON.stringify({ error: e.message }));
res.end();
});
} else {
res.end('path must end with json', 400);
}
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
@RandomEtc
Copy link
Author

See https://gist.github.com/2714281 for an Objective-C client that can't understand output from this server. Try opening http://localhost:1337/1/statuses/show/165946274644885504.json and compare with https://api.twitter.com/1/statuses/show/165946274644885504.json to see why.

@quartzjer
Copy link

Try http://localhost:1337/1/statuses/show/18829502573.json I think it's working fine for unicode, but emoji just won't render natively so you see <?>'s, but it's still valid utf8?

@pranavs80
Copy link

Hello,

i wanted to get the json data into node js.

can u please help me out with the code.

thanks
pranav

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment