Use eventEmitter or use method init()?

This is a two-part question as I'm curious what is the best method for my approach, as well as it might solve an error I get frequently.

I have a bunch of methods that need to be called before the app initializes such as custom WebSockets, setting/creating global.variables, and globs/readFileSyncs to gather mutable information from files to properly set certain widgets accordingly before the app starts. I'm wondering what is the best practice to put all these calls into.

I currently have them split between app.on("open", ...) and init(). I assumed this is the correct execution order of OSC (correct me if I'm wrong). Unload maybe doesn't exist in this chain, wasn't sure so I threw it at end.

// init -> created -> open -> sessionOpened -> 
// sessionClosed -> close -> destroyed -> unload

I was thinking init() was a perfect choice to do this in, since it's only called once at the beginning of the app. However, because my methods and creation of webSockets are slow struggling at roughly 9 seconds for all my calls to complete, it seems init() causes OSC to throw the following error:

(ERROR, HTTP) Could not setup http server, maybe try a different port ?

Sometimes, this error gets stuck in the sense that I just keep closing the app and restarting it until it finally boots up. Or, I'll mess with the following:

I'll split between app.on("open") and init(), then sometimes it opens fine, but sometimes I get the same error still. I'm wondering if the httpcheckTimeout is set too short, OR, if I may ask, there is a reason we're not logging the error? Could we add httpCheck(false, error) at line 188 to help with debugging if there is an error?

// src > server > server.js
// line 188 currently
http.get(settings.appAddresses()[0] + '/osc-ping', {
    auth: settings.read('authentication'),
    rejectUnauthorized: false
},()=>{}).on('error', ()=>{httpCheck(false)})  // send event error to httpCheck function

Thoughts?

Cheers,
DMDComposer

Having sync operations running for 9 seconds could be avoided by reading the files asynchronously to let the app init properly at the same time (since the http server uses a timeout to detect whether something went wrong).

Thank you Jean for the reply.

You're right, I'll rework the code to be asynchronous. I wanted things to spawn before the app loaded and for most things that still works. I'll rework to be asynchronous as it makes a lot more sense and will perform better, and not wait 9+ seconds to load the app haha.

Cheers!

About the app.on vs module.exports usage : at some point I'd like to expose a unified interface that relies only on events instead of having to export specific functions, like what app.on offers but with some dedicated and documented events for the custom module scope.

1 Like