2

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

sascha
  • 4,671
  • 3
  • 36
  • 54

2 Answers2

4

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

Community
  • 1
  • 1
Max
  • 8,671
  • 4
  • 33
  • 46
  • Okay, thank you so far for your answer! I already found that, but I missed something to delete the entry from `require.cache`: full path. As in the example `require.resolve` helped in this case. But there's still one problem: the output of my function still appears nth times, which means the function is still in memory. Any idea? – sascha Nov 20 '12 at 20:34
3

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');
        }
    });
}
sascha
  • 4,671
  • 3
  • 36
  • 54