慕標琳琳
2023-10-14 10:07:36
我正在嘗試關閉 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條經(jīng)驗 獲得超8個贊
首先,不要從error
事件處理程序中拋出錯誤。每當未捕獲異常時,節(jié)點進程就會崩潰。正如所寫的,您的代碼保證您的應用程序?qū)⒃?Twitter 連接出現(xiàn)問題時崩潰。
您可能想要記錄錯誤,然后有辦法恢復連接和/或通知實例化此代碼的人出現(xiàn)了問題。
接下來,請注意stream.destroy()
文檔:
在此調(diào)用之后,可寫流已結(jié)束,后續(xù)對
write()
或 的調(diào)用end()
將導致ERR_STREAM_DESTROYED
錯誤。
write
據(jù)推測,在您銷毀后有東西正在調(diào)用,這就是導致該error
事件的原因。
但是,您不應該error
在正常關閉過程中收到事件。

慕尼黑的夜晚無繁華
TA貢獻1864條經(jīng)驗 獲得超6個贊
您是否嘗試在銷毀流之前刪除偵聽器?
setTimeout(() => {
console.log('Closing stream...');
stream.removeAllListeners('data');
stream.removeAllListeners('error');
stream.destroy();
}, 1000);
添加回答
舉報
0/150
提交
取消