electron 如何让chokidar手表保持运行在后台的电子JS/ NodeJS

20jt8wwn  于 2022-12-16  发布在  Electron
关注(0)|答案(1)|浏览(240)

我正在使用chokidar库来跟踪文件。所以我创建了这个函数:

function StartWatcher(username){
    console.log(username)
    const chokidar = require('chokidar');
    const folderLocation='watch-folder'

    const watcher = chokidar.watch(folderLocation,{
        persistent: false,
        ignoreInitial: true,
        ignored: [ 'watch-folder/ignore-1.txt', 'watch-folder/ignore-2.txt' ],
        ignorePermissionErrors: false,
        interval: 100,
        binaryInterval: 300,
        disableGlobbing: false,
        enableBinaryInterval: true,
        useFsEvents: false,
        usePolling: false,
        atomic: true,
        followSymlinks: true,
        awaitWriteFinish: false
    })
    
    watcher.on('ready',async()=>{
        console.log("I am ready to watch files for ",username)
        console.log(folderLocation)
    })

    watcher.on('add',async (path) => {
        console.log(path,'File Path ....... for',username)
        var today = new Date();
        var fileAddingDate=today.getDate()+"/"+(today.getMonth()+1)+"/"+today.getFullYear()+" "+today.getHours()+":"+today.getMinutes()+":"+today.getSeconds()
        fs.readFile(path,async function(error,data){
            console.log(data)
        })
    })

    watcher.on('change',async (path)=>{
        console.log(path,'Content change in the file... for',username);
        var today = new Date();
        var fileAddingDate=today.getDate()+"/"+(today.getMonth()+1)+"/"+today.getFullYear()+" "+today.getHours()+":"+today.getMinutes()+":"+today.getSeconds()
        fs.readFile(path,async function(error,data){
          console.log(data)
        })
    })
}

现在我在这样的条件下调用这个函数。
启动监视器(删除盘卷)
但我有问题。只有就绪事件是工作。其余所有事件都不工作。我认为这是因为当我调用函数时,它只执行了一次,并停止。需要一些帮助。

whhtz7ly

whhtz7ly1#

我不知道你是否找到了这个问题的解决方案,但是,看看你的函数和发生在你身上的事情,你的问题是你把“persistent”设置为“false”,这导致在“ready”事件之后没有更多的事件被发射,因为你可以签入它的API:https://www.npmjs.com/package/chokidar#user-content-persistence

相关问题