如何创建一个的NodeJS流API [英] How to create a streaming API with NodeJS

查看:119
本文介绍了如何创建一个的NodeJS流API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你会如何去创建节点流API?就像 Twitter的流API

How would you go to create a streaming API with Node? just like the Twitter streaming API.

我想最终做的就是从 FriendFeed的API 第一次更新,当一个新的可用流(如ID不同),后来在其公开为Web服务,以便我可以在我的网站的WebSockets使用它。)

What I want to do ultimately is get the first update from the FriendFeed api, and stream when a new one becomes available (if the id is different), and later on expose it as a web service so I can use it with WebSockets on my website :).

到目前为止,我有这样的:

So far I have this:

var sys = require('sys'),
    http = require('http');

var ff = http.createClient(80, 'friendfeed-api.com');
var request = ff.request('GET', '/v2/feed/igorgue?num=1', 
                         {'host': 'friendfeed-api.com'});

request.addListener('response', function (response) {
    response.setEncoding('utf8'); // this is *very* important!
    response.addListener('data', function (chunk) {
        var data = JSON.parse(chunk);
        sys.puts(data.entries[0].body);
    });
});
request.end();

其中仅会从FriendFeed的数据,创建具有节点HTTP服务器是容易的,但它不能返回流(或者我还没有找到如何)。

Which only gets the data from FriendFeed, creating the Http server with node is easy but it can't return a stream (or I haven't yet found out how).

推荐答案

您想设置一个跟踪传入的请求,并存储它们的响应对象的系统。然后,当它的时间流从FriendFeed的一个新的事件,通过他们的响应对象和反应[I] .WRITE('东西')迭代出来给他们。

You would want to set up a system that keeps track of incoming requests and stores their response objects. Then when it's time to stream a new event from FriendFeed, iterate through their response objects and responses[i].write('something') out to them.

查看 LearnBoost的Socket.IO节点的,你甚至可能仅仅能够使用该项目作为你的框架,而不是有code它自己。

Check out LearnBoost's Socket.IO-Node, you may even just be able to use that project as your framework and not have to code it yourself.

从Socket.IO节点的示例应用程序(聊天):

From the Socket.IO-Node example app (for chat):

io.listen(server, {

    onClientConnect: function(client){
        client.send(json({ buffer: buffer }));
        client.broadcast(json({ announcement: client.sessionId + ' connected' }));
    },

    onClientDisconnect: function(client){
        client.broadcast(json({ announcement: client.sessionId + ' disconnected' }));
    },

    onClientMessage: function(message, client){
        var msg = { message: [client.sessionId, message] };
        buffer.push(msg);
        if (buffer.length > 15) buffer.shift();
        client.broadcast(json(msg));
    }

});

这篇关于如何创建一个的NodeJS流API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆