Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
How to load scripts from files into the javascript runtime

I have written a class that can load scripts from files into the runtime and then can execute those scripts - essentially a plugin system.

class Broker {
   constructor(){

       this.requests = require("../../plugins/sync/core")
       
   }
}

The scripts will also import this class, as they extend the class's capabilities.

const { Broker } = require("../../core/Broker");

module.exports = {
    isConnectableNode: {
        minRole: 2,
        script: async (data) => {
            ...
            let node = Broker.findNode(data.nodeID); // ERROR: Broker is undefined
            ...
        },
    },...

The script is called in this function within the Broker class:

async handleRequest(handler, data, user) {
        try {
            if (this.requests[handler].minRole >= user.role) {
                const res = await this.requests[handler].script(data);
                return res;
            } else {
                return { status: 401, message: "Not authorized." };
            }
        } catch (e) {
            return { status: 400, message: "Unknown Request." };
        }
    }

What works is calling a function that sets this.requests from within handleRequest() when it is empty or not initialized.

if (!this.requests) this.loadPlugins();

Now all imports are correctly loaded and available to the scripts.

Does anybody know the reason this only works when required from the closure of the handler Function and not the constructor or really anywhere outside?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!