Search code examples
javascriptstringnode.jsprimitive

Monitor primitive String declaration


Is there ANY way of monitoring primitive String declaration in NodeJS? For example, when I do "test"; is there any way of triggering a special event with "test" as a parameter?


Solution

  • I am not sure what you mean by do "test;"; but if you want to trigger an event whenever a variable is assigned a new value, no, there is no way to trigger an event for variable changes.

    If you want to watch a variable, it is better to re-design your system to make a call instead of assigning a variable. Instead of doing:

    running_mode = "test";
    

    require

    switch_mode("test");
    

    and call whatever event handlers you want to trigger on this update.

    If you really want to watch the value of a global variable, you can do it by checking the value once in every turn of the main loop:

    function is_mode_changed() {
       if (running_mode=="test") event_handler();
       process.nextTick(is_mode_changed);
    }
    

    Once you call this function, it will continue running once each turn of the main loop. If it what you want to do is something like following a variable to do some specific tasks time to time, like following a global counter and doing some cleanup tasks everytime counter reaches 1000, this is a good way to do. If what you want to do something immediately after a variable is changed, it is not possible.

    I hope I could understand your question correctly.

    UPDATE

    [I am adding this in regards to the comment below which rendered everything above unrelated to question because I had misunderstood it.]

    As you mentioned yourself, a string literal like "test" is a primitive value which is not an object. So, it is handled by the interpreter in a way we cannot alter.

    From Ecma-262:

    4.3.2 primitive value

    member of one of the types Undefined, Null, Boolean, Number, or String as defined in Clause 8

    NOTE: A primitive value is a datum that is represented directly at the lowest level of the language implementation.

    To prevent confusion, Clause 8 is the section of standard on Types as listed above.