1

I made this code:

var Discord = require('discord.js');
var client = new Discord.Client();
var fs = require('fs');
var dotenv = require('dotenv');
var option = require('./assets/config.json');
dotenv.config({
    path: __dirname + '/assets/.env'
});
client.on('ready', function () {
    console.log(`Logged in as ${client.user.tag}`);
});
client.on('message', function (message) {
    var done = false;
    if (!message.content.startsWith('/')) return;
    var args = message.content.substr(1).split(' ');
    fs.readdir('./cmd/', function (err, list) {
        for (var i = 0; i < list.length; i++) {
            var cmds = require(`./cmd/${list[i]}`);
            for (var x = 0; x < cmds.alises.length; x++) {
                for (var a = 0; a < args.length; a++) {
                    if (args[a] == cmds.alises[x] && !done) {
                        cmds.run(client, message, args, option);
                        done = true;
                    }
                }
            }
        }
    });
});
client.login(process.env.TOKEN);

And I thought that I don't have to restart this main file when I edit the module files because in this code Node.js reads all the files instantly on messages. But when I edit the module file, I should restart the main file. Why is this thing happens?

mswgen
  • 636
  • 1
  • 9
  • 18
  • 2
    Node [caches required modules](https://nodejs.org/api/modules.html#modules_caching). One common pattern is to use [nodemon](https://www.npmjs.com/package/nodemon) or something like it to restart node after changes in development. If you really want to reload all of the modules every time a message is sent, it is possible to [invalidate the cache for a module](https://stackoverflow.com/q/9210542/996081), but I would advise you to load the modules once when the app starts. – cbr Mar 16 '20 at 09:49
  • To clarify what cubrr said in comparison with what you said you had thought. fs reads are often used to avoid needing to clear the cache or restart the program for changes to JSON files, but that is only for JSON files which can also be required. This won't work with your JS scripts because required statements always cached. So, for example, I see you are using a config.json. If you want to be able to change that outside your JS app, and have the changes take immediate effect, you need to use fs to read and write it rather than require. – Tarazed Mar 16 '20 at 13:30

0 Answers0