mercredi 7 mars 2018

Dynamically load a class in node js

I've a node module, and I want to pass as a command line a name of another module to load in order to perform some work in a configurable way ( ie: I can choose which module to load to perform different works ) I'm using something like this:

var persister;
if(argv.p) //this is my module name as an argument
{
    var Persister = require(argv.p);
    persister = new Persister();
}

a sample module is defined as:

'use strict';



module.exports = class OneOfMyPersister{
    constructor(){

then, when I need to use i check if persister is defined and I call conventionally named methods to perform the work. This approach works, I just want to ask if it is a good approach, or if there is something better. The idea I want to imitate is like dynamically loading a plugin in Java or C#, when I use for instance Assembly.Load("filename") Is there some better way to do it in Node?

Aucun commentaire:

Enregistrer un commentaire