节点:试图停止流

时间:2018-10-13 04:27:07

标签: javascript node.js twitter http-error twitter-streaming-api

因此,我有一个带有输入文本的简单表单,用户可以搜索查询,单击“开始”,twitter流将启动...当用户单击“停止”按钮流时停止。

问题:我添加了一个emit事件,但是,当单击停止按钮时,它不起作用!即停止流

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

index.pug

 form#search-form(action='javascript:sendForm()', method='POST')
    input(type="text" name="searchTerm" placeholder="#hastag" required)
    button(type="submit"  name="startBtn" id="startBtn") Search
    button(type="submit" id="stopBtn" name="stopBtn") Stop

script.js

function sendForm() {
   $("#startBtn").on('click', function() {
    console.log("stared");
    let form = $('#search-form');
    let query = form.serialize();
    $.post('/', query, async function (data) {
        const results = await data;
    });

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

index.js

io.on('connection', function(socket) {

  // Socket Stream Button 
  const _stream = {};

  /* GET home page. */
  router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
  });


    router.post('/', async (req, res) => {
        twitterStream(socket, _stream, req.body.searchTerm, 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;
          });

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

        res.send("true");
    });
});
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);
      });

    // });
  }

0 个答案:

没有答案