#How do I run a piece of code once at startup?

25 messages · Page 1 of 1 (latest)

brazen crystal
#
(function() {
    var id_counter = 1;
    Object.defineProperty(Object.prototype, "__uniqueId", {
        writable: true
    });
    Object.defineProperty(Object.prototype, "uniqueId", {
        get: function() {
            if (this.__uniqueId == undefined)
                this.__uniqueId = id_counter++;
            return this.__uniqueId;
        }
    });
}());
#

If I were to use this code in my project, I would want it to run once and only once at startup

#

How do you design a typescript project to do run a snippet like the above in such a way?

#

Let me know if I'm not providing enough information. I don't know if the answer depends on the environment. My code will run in node.js, but I'm looking for a general-purpose answer if one exists.

#

If I couldn't ask, here's how I would do it:

  1. Put this code in a file
  2. Import that file at the top of index.ts (or whatever file is the main entry point).
gray lake
#

i'm not sure if the __unique_id is supposed to be the actual use of the function or attempting "one run only" or what
if it's the latter, i'd be attaching symbols to globalThis, but preferably not doing that at all and just importing the file normally
iirc both cjs and esm have caching so a repeated import doesn't rerun top-level code of that module

brazen crystal
gray lake
#

basically, the code that is the body of a module that's statically imported is already run once and only once at startup

brazen crystal
#

What do you mean by statically imported?

#

As opposed to dynamically imported?

gray lake
#

dynamic imports can be subject to logic/control flow, and they might be executed after initial loading (after startup)

#

with esm, that would be import vs import(), although if the latter is run in the body of a module then that's also done once on startup

#

with cjs, it's only really based on where the call is, since both cases would still use require

brazen crystal
#

Okay thanks. I had never heard the term "static import," but that's what I thought it meant

gray lake
#

i think it wasn't as concretely defined before esm was a thing

brazen crystal
gray lake
#

yes

brazen crystal
#

Okay that would work, but my main question is, is that idiomatic?

gray lake
#

what you're asking doesn't really sound like it's a niche case. all initialization code is intended for "once and only once at startup"

gray lake
#

i mean not even the module system, all top-level code is really only ever run once in basically every environment and language

brazen crystal
#

I assumed it's not idiomatic to have side effects on import, but I didn't know another way to achieve this

gray lake
#

there are some modules that are explictly and exclusively side effects

#

but maybe consider if you even need side effects