尝试停止流:TypeError:_stream.abort不是函数吗?

时间:2018-10-13 09:14:20

标签: javascript node.js socket.io twitter-streaming-api node-streams

我正在尝试使用Twitter Stream API创建流。

  • 我有一个开始按钮,用于开始直播。

  • 我有一个停止按钮以停止流播放。

我使用Web套接字,由此单击“开始”按钮时,我开始在服务器端进行流式传输。 当单击“停止”按钮时,我将销毁流_stream.abort() (我尝试过_stream.destroy()-同样的错误)

index.js(服务器端)

io.on('connection', function(socket) {
 // Socket Stream Button 
  const _stream = {};

  // Destroy on stopBtn is clicked
  socket.on('myapp:search', function(term) {
  console.log('received a new search:', term);
    _stream.abort();
  });

  // Listen to Start Button being clicked, value is emitted, start twitter stream
  socket.on('startStreaming', function()  {
    console.log("arguments::: ",arguments['0'])
    twitterStream(socket, _stream, arguments['0'], function(_stream) {
      _stream.on('data', function(tweet) {
        console.log(tweet.text + "Streaming");
        // socket.emit('tweet', tweet.text);
      });

      _stream.on('error', function(error) {
        console.log("erorr:: " + error);
        throw error;
      });

    });

  });
}

function twitterStream(socket, _stream, term, callback) {
    // return new Promise((resolve, reject) => {

      console.log("TERM _" +term);
      client.stream('statuses/filter', { track: term }, function(stream) {
        _stream = stream;

        callback(_stream);
      });

    // });
  }

在这里,我只需单击“开始/停止”按钮即可触发发射事件。

Script.js(前端)

    function sendForm() {
       $("#startBtn").on('click', function() {
            //input(type="text" name="searchTerm" placeholder="#hastag" required)
            let searchTerm  = $("#searchedTerm").val();
            console.log(searchTerm);
            socket.emit('startStreaming', searchTerm, function(data) {
                console.log("stared");
            });
       }); 

       $("#stopBtn").on('click', function() {
            console.log("stop btn");
            socket.emit("myapp:search", function(data) {
                console("stopped stream" + data);
            }); 
        });
    }
  

错误节点控制台: TypeError:_stream.abort不是函数

Desktop/assign2/routes/index.js:41
    _stream.abort();
  

错误浏览器控制台:

The connection to ws://localhost:3000/socket.io/?EIO=3&transport=websocket&sid=ZZusoZ2GTYEGTebcAAAB was interrupted while the page was loading.

Source map error: TypeError: NetworkError when attempting to fetch resource.
    Resource URL: http://localhost:3000/socket.io/socket.io.js
    Source Map URL: socket.io.js.map[Learn More]

1 个答案:

答案 0 :(得分:1)

在文件的开头,脚本将_stream设置为空对象。因此,它稍后尝试调用的方法不存在。