static660
static660

Reputation: 81

How to evaluate classes from files applied globally using Eval - node.js

Parent script including childscript

    const fs = require('fs');
    
    function include(f) {
        eval.apply(global,[fs.readFileSync(f).toString()])
    }
    
    include(__dirname+'/fileToRead.js');

    
    
    
    hi();
    
   let childVar = new child();

------------------------- childScript ------------------------------

  function hi() {
        console.log("hi");
    }
    
    
    class baseObj {
        constructor(){
            console.log("hello")
        }
    
    }
    
    
    class child extends baseObj{
        constructor(){
           super();
    
        }
    }

----------------------------result-----------------------------------

// the hi function executes
hi

// the instance does not
let childVar = new child();  
^

ReferenceError: child is not defined

---------------------Conclusive question---------------------

how do would I get the eval method to globalize the child class as well as the baseObj class using my include method provided.

---------------------------------disclaimer------------------ Disclaimer : I know modules exist and I think they are great , but when you are doing something so large server side its a huge pain to keep track of exports and imports.

Especially since cyclic references exist. Not to mention every single time you create a file you need to add whatever functionality to it with require statements and find the path to those files and then export whatever functionality you are creating in that file to go to other files .

I wish to avoid modules using this method for the most part and make it similar to dealing with client side import statements.

Thanks for the help and have a nice day guys ! :)

Upvotes: 0

Views: 333

Answers (2)

vsemozhebuty
vsemozhebuty

Reputation: 13782

If you really-really need this, this is an option, as class (unlike var) does not create global bindings:

var baseObj = class {
  constructor() {
    console.log("hello")
  }
}

var child = class extends baseObj {
  constructor() {
    super();
  }
}

Upvotes: 1

georg
georg

Reputation: 214949

Your problem boils down to this:

eval('function foo() {}')
console.log(foo) // ok

eval('class bar {}')
console.log(bar) // nope

This is because

Bindings introduced by let, const, or class declarations are always instantiated in a new LexicalEnvironment. (https://tc39.es/ecma262/#sec-performeval, NOTE)

If you really want to replace the stock require, for whatever reason, try using the VM API (this is what require uses under the hood).

Upvotes: 2

Related Questions