我正在尝试关闭 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 1npm ERR! path /mnt/c/Users/john john/Desktop/tweetNodenpm ERR! command failednpm ERR! command sh -c node app.jsnpm 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;};
2 回答
料青山看我应如是
TA贡献1772条经验 获得超8个赞
首先,不要从error
事件处理程序中抛出错误。每当未捕获异常时,节点进程就会崩溃。正如所写的,您的代码保证您的应用程序将在 Twitter 连接出现问题时崩溃。
您可能想要记录错误,然后有办法恢复连接和/或通知实例化此代码的人出现了问题。
接下来,请注意stream.destroy()
文档:
在此调用之后,可写流已结束,后续对
write()
或 的调用end()
将导致ERR_STREAM_DESTROYED
错误。
write
据推测,在您销毁后有东西正在调用,这就是导致该error
事件的原因。
但是,您不应该error
在正常关闭过程中收到事件。
慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
您是否尝试在销毁流之前删除侦听器?
setTimeout(() => {
console.log('Closing stream...');
stream.removeAllListeners('data');
stream.removeAllListeners('error');
stream.destroy();
}, 1000);
添加回答
举报
0/150
提交
取消