【问题标题】:Watch for changes in a text file, and handling when this file doesn't exist监视文本文件中的更改,并在此文件不存在时进行处理
【发布时间】:2020-08-04 22:28:45
【问题描述】:

我最近一直在做一个项目,我基本上需要检查文本文件中的新文本。 我的代码是这样的:

const fs = require('fs');

fs.watch('./file.txt', (event, filename) => {
    fs.readFile('./file.txt', (err, data) => {
         if (err) throw err;
         data = JSON.parse(data);

         console.log(data);
    }
}

效果很好。但是,有时,我必须出于某种原因删除此文件,因此我的代码也崩溃了!

知道如何处理这个问题吗?谢谢你的回答

【问题讨论】:

    标签: javascript node.js fs


    【解决方案1】:

    Node 的内置模块fs 不能很好地支持文件删除检测。有一个使用名为nsfw 的包的解决方法,它是对本地库的包装,可为删除检测提供更好的支持。 API 有点奇怪,但它仍然是一个可靠的包。

    这是您尝试使用 nsfw 执行的操作的示例。

    const nsfw = require("nsfw");
    const path = require("path");
    const fs = require("fs");
    
    const file = path.join(__dirname, "file.txt");
    let watcher;
    nsfw(
        file,
        ([event, ...restEvents]) => {
            switch (event.action) {
                case nsfw.actions.DELETED: {
                    watcher.stop();
                    return; // or handle this however you need to..
                }
                default: {
                    fs.readFile(file, (err, data) => {
                        if (err) throw err;
    
                        try {
                            data = JSON.parse(data);
    
                            console.log(data);
                        } catch (error) {
                            console.error(error)
                        }
                    });
                }
            }
        }
    )
    .then((w) => {
        watcher = w;
        watcher.start()
    });
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多