Kiril
Kiril

Reputation: 331

Is it a good idea to use NodeJS global events via process?

I need to use setInterval to do queries to database each N seconds and fire results to all Socket.IO clients so I do it like this:

let interval_id = null

io.on('connection', function(socket) {
    if (interval_id == null) {

        interval_id = setInterval(function() {
            db.table.items.getAll().then(function(items) {
                process.emit('items_found', items)
            }).catch(function(err) {
                log.error(err)
            })
        }, config.scan.interval)
    }

    process.on('alarms_found', function(alarms) {
        console.log(alarms.length)
    })
})

It's working fine but I'm newbie in NodeJS and I don’t know any other ways to do this... In general I understand that usage of global scope is not the best idea, but I don’t know others...

Upvotes: 3

Views: 402

Answers (1)

Gireesh Punathil
Gireesh Punathil

Reputation: 1374

  • If your real code is same, or similar with respect to volume and complexity, this approach does not impose any issues. Process object is an EventEmitter, and here you leverage it effectively.
  • If not, it is a good idea to use an eventemitter of your own, instead of process object. By design, it represents vital parameters of the running node process such as execution environment, node modules, and other OS abstractions. The EventEmitter inheritance helps it to manage the process lifecycle events.
  • Cluttering it with custom application data flow will not cause any functional issues, but when application grows, the maintenance and problem determination become difficult. For example if you also happen to store the 'alarms' (either entirely, or a subset of it) at every intervals, the storing object will grow indefinitely and never to be garbage-collectable. ii) Even after you are finished with the DB related activities, the listener will continue to be active, along with any memory it held up. You can actually work around that in this scenario by naming the callback function (say foo), and remove the callback by issuing process.removeListener('alarms_found', foo) when not required.

Upvotes: 2

Related Questions