【问题标题】:fs.existsSync is not waiting for fs.readFile inside iffs.existsSync 不等待 fs.readFile 里面 if
【发布时间】:2021-08-14 22:41:34
【问题描述】:
if (fs.existsSync('tmp/cache.txt')) {
        fs.readFile("tmp/cache.txt", function (err, data) {
            if (data != "" || data != "[]") {
                jdata = JSON.parse(data);
                if (
                    jdata[jdata.length - 1].substring(4, 8) ==
                    new Date().getFullYear() + 543
                ) {
                    year = new Date().getFullYear() + 542;
                    console.log("yes this year");
                }
                jdata.forEach(function (value, i) {
                    if (
                        value.substring(4, 8) ==
                        new Date().getFullYear() + 543
                    ) {
                        countloveme--;
                    }
                });
                jdata.splice(countloveme);
            }
        });
    }

我的代码正在运行,但是

代码在 ifelse 中的 fs.readFile 完成之前完成

我不知道如何在 fs.readFile 中添加 await 或无论如何此代码正在工作

【问题讨论】:

  • 您似乎知道exists 的同步版本,但不知道readFile,并指出掌握一般异步编程仍然是个好主意。
  • fs.readFile() 是非阻塞和异步的,因此您的代码不会等待它完成。如果您的应用程序中的同步代码正常(例如,它不是服务器),那么您可以使用fs.readFileSync()。否则,您需要学习如何在 nodejs 中编写正确的异步代码,并且我们需要先查看周围的代码上下文,然后才能提出正确的编写方法,因为调用代码也必须更改。

标签: node.js fs


【解决方案1】:

如cmets中所写,使用fs,readFileSync会是更好的选择

当您使用Array.forEach() 时,您正在启动一个同步运行的新功能。

我已经清除了你的代码,也许这可以帮助你

if (fs.existsSync('tmp/cache.txt')) {

    try {
        const data = fs.readFileSync("tmp/cache.txt");
        if (!data || data != "" || data != "[]")
            throw new Error('tmp/cache.txt file is empty');

        const jdata = JSON.parse(data);

        // More clear to use variables in the if elses
        const arg1 = jdata[jdata.length - 1].substring(4, 8)
        const arg2 = new Date().getFullYear() + 543;

        if (arg1 === arg2) {
            // You don't use this date anywhere?
            new Date().getFullYear() + 542;
            console.log("yes this year");
        }
        
        for (let dataChunk of jdata) {
            if (
                dataChunk.substring(4, 8) ==
                new Date().getFullYear() + 543
            ) {
                countloveme--;
            }
        }
        jdata.splice(countloveme);

    } catch (error) {
        console.error(error.message);
    }

}

【讨论】:

    猜你喜欢
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 2018-12-09
    • 1970-01-01
    • 2021-11-28
    • 2018-05-04
    • 2020-05-09
    相关资源
    最近更新 更多