sascha
sascha

Reputation: 4690

Load + overwrite function at runtime

I was trying to create an IRC bot written in Javascript + NodeJS. This bot should be able to load plugins while running and should be able to reload the same plugin after changes etc.

What works?

Loading files at runtime + executing its code.

What's wrong?

After loading the same plugin again if still executes my code, but now it happens twice or nth times I load the plugins.

Current code:

bot.match(/\.load/i, function(msg) {
    require('./plugins/plug.js')(this);
});

module.exports  = function(bot) {
    bot.match(/\.ping/i, function(msg) {
    msg.reply('pong');
});

So, is there any way to fix my issues and make this work?

P.s. I'm using IRC-JS as a base for this bot.

updated, fixed:

Even changes to that file are ignored, so it must be something like a cache.

Fixed by clearing the require.cache

Upvotes: 2

Views: 1098

Answers (2)

sascha
sascha

Reputation: 4690

To answer my own question. While loading plugins, I add every object to a global array. This can be easily accessed and deleted afterwards.

function clearplugins() {
    require("fs").readdirSync("./plugins/active").forEach(function(file) {
        delete require.cache[require.resolve("./plugins/active/" + file)];
    });

    plugins.forEach(function(obj) {
        obj();
    });
}

function loadplugins() {
    require("fs").readdirSync("./plugins/active").forEach(function(file) {

        if(file.slice(-2) == 'js') {
            plugins.push(require("./plugins/active/" + file)(bot));
            console.log(file+' loaded');
        }
    });
}

Upvotes: 3

Max
Max

Reputation: 8836

require won't reload a file. Once it has been loaded once, it is in memory and it will not reload again. It sounds like you want to leave the bot on and change the contents of the scripts it requires 'on the fly'. You can do that by deleting require.cache. Check out node.js require() cache - possible to invalidate? and http://nodejs.org/api/modules.html#modules_caching

Upvotes: 4

Related Questions