Skip to content
Advertisement

How do I re-run a Javascript-file when the content of a folder changes?

I am having trouble getting this to work. I am developing a Discord-bot and just started using slash-commands, which require the commands to be “pushed” every time I change something. The files are pushed by simply running a Javascript-file. Then there is also the main bot-file, which needs to be stopped from running and then started again, in order for the changes to take affect. However, I do not want to have to manually stop the bot process, push the changes and then run the bot process again, every time there are changes. I already experimented with the Node.js “FileSystem.watch()” command and got it to detect changes in the folder, the bot command-files are stored in. This is the code I have right now:

const fs = require('fs');

fs.watch('commands', function (event, filename) {

    if(event === 'change'){
        console.log(`changes`)
    }
});

I now need to connect this to the starting and restarting of the two files I mentioned, but am a little bit stuck. Can I build on top of my setup and just run the files from there or do I need to take another approach?

Any help is greatly appreciated! 🙂

Advertisement

Answer

  1. Install nodemon as a dev dependency: npm i -D nodemon
  2. Create a new script on package.json like this:
{
  "scripts": {
    "dev": "nodemon YOUR_FILE.js"
  },
  "devDependencies": {
    "nodemon": "^2.0.16"
  }
}

  1. Then just run the command npm run dev 😉
Advertisement