R
R
Ruslan Samara2021-08-28 10:12:57
Node.js
Ruslan Samara, 2021-08-28 10:12:57

How to prevent memory leak in node.js events?

I receive new messages from one service, only these new messages I need to filter.
The filter comes from another server and must exist for a certain time.
Hence 2 problems:
1. Memory leak when new messages are received.

eventEmitter.on('NEW_MESSAGE', (msg) => {
  // При каждом новом сообщении будет создавать новую прослушку
  ws.on('FILTER', async (filter) => {
    // отправляем ответ на сервер
    await sendMsg(msg, filter)
  })
})

2. These filters need to be resolved so as not to clog memory with unnecessary objects.
I do so. With the current implementation, this works.
const sendMsg = async (msg, filter) => {
  try {
    // Отправляем если фильтр соответствует
    if (msg.id === filter.id) {
      ws.emit('FILTER', msg)
    }
    if(msg.status === filter.status || msg.status === 'completed') {
      resolve(msg)
    }
  } catch (error) {
    rejects()
  }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question