猿问

如何在不关闭 Nodejs 服务器的情况下停止流

我正在尝试关闭 Twitter 流。问题是它关闭了我的服务器,我必须重新启动它。有没有办法在不关闭 Nodejs (express) 服务器的情况下关闭流。这是我收到的错误:


file:///mnt/c/Users/john%20john/Desktop/tweetNode/controllers/utils.js:21

    throw new Error('something bad happened');

Error: something bad happened

    at Parser.<anonymous> (file:///mnt/c/Users/john%20john/Desktop/tweetNode/controllers/utils.js:21:11)

    at Parser.emit (node:events:376:20)

    at IncomingMessage.<anonymous> (/mnt/c/Users/john john/Desktop/tweetNode/node_modules/twitter/lib/twitter.js:288:14)

    at IncomingMessage.emit (node:events:388:22)

    at TLSSocket.socketCloseListener (node:_http_client:442:13)

    at TLSSocket.emit (node:events:388:22)

    at node:net:661:12

    at TCP.done (node:_tls_wrap:564:7)

npm ERR! code 1

npm ERR! path /mnt/c/Users/john john/Desktop/tweetNode

npm ERR! command failed

npm ERR! command sh -c node app.js


npm ERR! A complete log of this run can be found in:

npm ERR!     /home/johnjohn/.npm/_logs/2020-12-06T02_19_10_092Z-debug.log

这是代码


import Twitter from 'twitter';

import ck from 'ckey';


let twitter = new Twitter({

  consumer_key: ck.TWITTER_CONSUMER_KEY,

  consumer_secret: ck.TWITTER_CONSUMER_SECRET,

  access_token_key: ck.TWITTER_ACCESS_TOKEN_KEY,

  access_token_secret: ck.TWITTER_ACCESS_TOKEN_SECRET,

});


export const stream = (term, clients) => {

  let stream = twitter.stream('statuses/filter', { track: term });

  stream.on('data', function (tweet) {

    console.log('tweetsJohn: ');

    broadcast(clients, JSON.stringify(tweet));

  });


  stream.on('error', function (error) {

    // throw error;

    throw new Error('something bad happened');

  });


  setTimeout(() => {

    console.log('Closing stream...');

    stream.destroy();

  }, 1000);


  // return stream;

};


慕标琳琳
浏览 114回答 2
2回答

料青山看我应如是

首先,不要从error事件处理程序中抛出错误。每当未捕获异常时,节点进程就会崩溃。正如所写的,您的代码保证您的应用程序将在 Twitter 连接出现问题时崩溃。您可能想要记录错误,然后有办法恢复连接和/或通知实例化此代码的人出现了问题。接下来,请注意stream.destroy()文档:在此调用之后,可写流已结束,后续对write()或 的调用end()将导致ERR_STREAM_DESTROYED错误。write据推测,在您销毁后有东西正在调用,这就是导致该error事件的原因。但是,您不应该error在正常关闭过程中收到事件。

慕尼黑的夜晚无繁华

您是否尝试在销毁流之前删除侦听器?setTimeout(() => {&nbsp; console.log('Closing stream...');&nbsp; stream.removeAllListeners('data');&nbsp; stream.removeAllListeners('error');&nbsp; stream.destroy();}, 1000);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答