LoginSignup
3
3

More than 5 years have passed since last update.

node-twitterのstreamを止める方法

Last updated at Posted at 2015-12-22

止め方についての情報が少なかったのでメモ
対象はnode-twitter
forkがたくさんあるけど、現在はこれが主流みたい?

オリジナルのnode-twitterのリポジトリ見たら書いてました。

twit.stream('user', {track:'nodejs'}, function(stream) {
    stream.on('data', function(data) {
        console.log(util.inspect(data));
    });
    // Disconnect stream after five seconds
    setTimeout(stream.destroy, 5000);
});

どうやら、コールバックに渡されるstreamに停止するためのメソッド(destroy)が用意されているみたいです。

コールバック内の変数はアクセスしにくいので、下のように外の変数に入れてあげると良さそうです。(あまり綺麗には見えませんが)

var currentTwitStream = null;
twit.stream('user', {track:'nodejs'}, function(stream) {
    stream.on('data', function(data) {
        console.log(util.inspect(data));
    });
    currentTwitStream = stream;
});

function stopStream() {
    if(currentTwitStream) {
        currentTwitStream.destroy();
        currentTwitStream = null;
    }
}

stopStreamのように停止用の関数を作ると扱いやすいかもしれません。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3