Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda