简体   繁体   English

当文件夹的内容发生变化时,如何重新运行 Javascript 文件?

[英]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.我正在开发一个 Discord-bot,刚开始使用斜杠命令,每次更改时都需要“推送”命令。 The files are pushed by simply running a Javascript-file.只需运行 Javascript 文件即可推送文件。 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.然后还有主 bot 文件,需要停止运行然后重新启动,以使更改生效。 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:我已经尝试过使用 Node.js“FileSystem.watch()”命令并让它检测文件夹中的更改,bot 命令文件存储在其中。这是我现在拥有的代码:

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!任何帮助是极大的赞赏! :) :)

  1. Install nodemon as a dev dependency: npm i -D nodemon安装 nodemon 作为开发依赖项: npm i -D nodemon
  2. Create a new script on package.json like this:在 package.json 上创建一个新脚本,如下所示:
{
  "scripts": {
    "dev": "nodemon YOUR_FILE.js"
  },
  "devDependencies": {
    "nodemon": "^2.0.16"
  }
}

  1. Then just run the command npm run dev ;)然后只需运行命令npm run dev ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM