Search code examples
node.jsntwitter

A Node app that runs in development but stops in production


I am having trouble finding what's wrong with my code. This app runs fine if I run "node whatever.js" but once I push it up to production in a place like Nodejitsu, it fails to run (I'm actually not sure if it fails to run, but I think it just runs once right after I activate the server, and then stops running for all requests afterwards). (I deleted my keys and tokens information for privacy)

P.S: the actual app is hosted here: http://bucifer-realtime-twitter.jit.su/ The "wait for it" in the template is supposed to change into a whole bunch of twitter data using socket.io/Express, which works fine in development.

var express = require("express");
var fs = require("fs");
var http = require("http");
var https = require("https");
var port = "1337";
var twitter = require('ntwitter');

var twit = new twitter({
  consumer_key: 'x',
  consumer_secret: 'x',
  access_token_key: 'x',
  access_token_secret: 'x'
});

var app = express();
app.get("/", function(request, response) {
  var content = fs.readFileSync(__dirname + "/template.html");
  response.setHeader("Content-Type", "text/html");
  response.send(content);
});
var server = http.createServer(app);
server.listen(port);

var io = require('socket.io').listen(server);

app.use(express.static(__dirname + '/public'));

twit.stream('statuses/filter', { track: ['naruto'] }, function(stream) {
  stream.on('data', function (tweet) {
    console.log("working...");
    io.sockets.emit("tweet", tweet);
  });
  stream.on('end', function() {
    console.log("Disconnected");
    io.sockets.emit('ending', {message: 'test'});
  });
  stream.on('error', function(error ,code) {
    console.log("My error: " + error + ": " + code);
  });
  // Disconnect stream after -- seconds
  var myTimeOut = 21000;
  setTimeout(stream.destroy, myTimeOut);
});

Solution

  • To summarize the comments above, in case anyone else has a similar situation ...

    The lines

    // Disconnect stream after -- seconds
    var myTimeOut = 21000;
    setTimeout(stream.destroy, myTimeOut);
    

    disconnect the Twitter feed, so users are still served a page with an active socket.io connection, but there's nothing listening to Twitter to update them.

    If Twitter is throttling the ability to listen, then the code quoted above needs to take a different approach, by either intermittently waking up to check messages, going dormant intermittently when bytes/message/whatever thresholds are nearing unacceptable levels, etc. Twitter will have no insight to the socket.io connection, so there's you don't need to limit that traffic for their sake.