如何使用 NodeJS 创建流 API [英] How to create a streaming API with NodeJS

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

问题描述

您将如何使用 Node 创建流式 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获取数据,用node创建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 流式传输新事件时,遍历它们的响应对象并将 responses[i].write('something') 输出给它们.

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-Node,您甚至可以将该项目用作您的框架,而不必自己编写代码.

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-Node 示例应用程序(用于聊天):

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天全站免登陆