Construire une API nodejs simple avec une sortie JSON en streaming

J’essaye de construire une API de streaming simple basée sur node.js. Tout ce que je veux faire, c’est que lorsque je frappe l’URL du serveur, la sortie doit diffuser un dataset de test (JSON) comme l’API de diffusion en continu de Twitter.

var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); server.listen(8083); app.get('/', function (req, res) { res.write(io.on('connection', function (socket) { socket.emit('item', { hello: 'world' }); })); }); 

Donc, si je fais curl http://localhost:8083/ , je veux sortir quelque chose comme:

 $ curl http://localhost:8083/ {hello: 'world'} {hello: 'world'} {hello: 'world'} {hello: 'world'} ... 

Je suis nouveau sur node.js et les sockets web. Je me trompe peut-être horriblement sur les bases du fonctionnement du nœud, laissez-moi savoir la meilleure solution.

Premièrement, il est préférable de placer la partie JSONStream dans un middleware comme ceci:

 var _ = require('lodash'); // https://github.com/smurthas/Express-JSONStream/blob/master/index.js function jsonStream(bytes) { return function jsonStream(req, res, next) { // for pushing out jsonstream data via a GET request var first = true; var noop = function () {}; res.jsonStream = function (object, f) { f = _.isFunction(f) ? f : noop; if (!(object && object instanceof Object)) { return f(); } try { if (first) { first = false; res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' }); } res.write(JSON.ssortingngify(object) + '\n'); } catch (err) { return _.defer(f.bind(null, err)); } f(); }; next(); }; } 

Ensuite, supposons que vous souhaitiez être averti via cette API chaque fois que quelqu’un se connecte à socket.io

 var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); var _ = require('lodash'); var EventEmitter = require('events').EventEmitter; server.listen(8083); var mediator = new EventEmitter(); io.on('connection', function (socket) { mediator.emit('io:connection:new', socket); }); // the second parameter, specify an array of middleware, // here we use our previously defined jsonStream app.get('/', [jsonStream()], function (req, res) { function onNewConnection(socket) { res.jsonStream({ type: 'newConnection', message: 'got a new connection', socket: { id: socket.id } }); } // bind `onNewConnection` on the mediator, we have to use an mediator gateway // because socket.io does not offer a nice implementation of "removeListener" in 1.1.0 // this way each time someone will connect to socket.io // the current route will add an entry in the stream mediator.on('io:connection:new', onNewConnection); // unbind `onNewConnection` from the mediator // when the user disconnects req.on('close', function () { mediator.removeListener('connection', onNewConnection); }); res.jsonStream({ type: 'welcome', message: 'waiting for connection' }); }); 

Enfin, si vous souhaitez tester ce code sans vous connecter à socket.io, utilisez le simulateur suivant:

 // Simulate socket.io connections using mediator (function simulate() { var dummySocket = { id: ~~(Math.random() * 1000) }; mediator.emit('io:connection:new', dummySocket); setTimeout(simulate, Math.random() * 1000); })();