检查文件是否在fs中后无法读取文件

时间:2019-09-09 23:20:37

标签: node.js filesystems fs

所以我试图在读取文件之前检查文件是否存在,但是如果我在读取之前进行检查,即使数据存在,读取也将一无所获。

我尝试将其放在下面,但是尝试从空白文件读取文件时,我的文件只会出现错误。

bot.on('chat', function(username, message) {
            var time = clock.zonedDateTime('SYSTEM').toString()
            if (!fs.existsSync('C:/Users/La Fam/Desktop/kekbot_rewritten(tm)' + '/players/' + username)) {
                fs.mkdirSync('C:/Users/La Fam/Desktop/kekbot_rewritten(tm)' + '/players/' + username);
            }
            if (!fs.existsSync('C:/Users/La Fam/Desktop/kekbot_rewritten(tm)' + '/players/' + username + '/lirstwords/')) {
                fs.mkdirSync('C:/Users/La Fam/Desktop/kekbot_rewritten(tm)' + '/players/' + username + '/lirstwords/');
            }
            if (!fs.existsSync('C:/Users/La Fam/Desktop/kekbot_rewritten(tm)' + '/players/' + username + '/lirstwords/lastwords/')) {
                fs.mkdirSync('C:/Users/La Fam/Desktop/kekbot_rewritten(tm)' + '/players/' + username + '/lirstwords/lastwords/');
            }


            if (!fs.existsSync('C:/Users/La Fam/Desktop/kekbot_rewritten(tm)' + '/players/' + username + '/lirstwords/lastwords/' + 'firstwords.txt')) {
                fs.writeFile('C:/Users/La Fam/Desktop/kekbot_rewritten(tm)' + '/players/' + username + '/lirstwords/lastwords/' + 'lastwords.txt', 'sentat:' + time + ',<' + username + '>' + message, 'utf8', function(err) {
                    if (err) throw err;

                });
            }

            if (message.startsWith('!lastwords ')) {
                if (cooldown == 1) {
                    var lastwordsplit = message.toString().split(" ")
                    var lastwordperson = lastwordsplit[1]
                    if (fs.existsSync('C:/Users/La Fam/Desktop/kekbot_rewritten(tm)/players/' + lastwordperson + '/lirstwords/lastwords/lastwords.txt')) {
                        bot.chat(fs.readFileSync('C:/Users/La Fam/Desktop/kekbot_rewritten(tm)/players/' + lastwordperson + '/lirstwords/lastwords/lastwords.txt', 'utf8'))
                        console.log('C:/Users/La Fam/Desktop/kekbot_rewritten(tm)/players/' + lastwordperson + '/lirstwords/lastwords/lastwords.txt')

                    }
                    if (!fs.existsSync('C:/Users/La Fam/Desktop/kekbot_rewritten(tm)/players/' + lastwordperson + '/lirstwords/lastwords/lastwords.txt')) {
                        bot.chat(" does not have any documents that include the user " + lastwordperson)
                        if (!fs.existsSync('C:/Users/La Fam/Desktop/kekbot_rewritten(tm)' + '/players/' + username + '/lirstwords/lastwords/' + 'firstwords.txt')) {
                            fs.writeFile('C:/Users/La Fam/Desktop/kekbot_rewritten(tm)' + '/players/' + username + '/lirstwords/lastwords/' + 'lastwords.txt', 'sentat:' + time + ',<' + username + '>' + message, 'utf8', function(err) {
                                if (err) throw err;

                            });
                        }
                    }

                }
            }
});

1 个答案:

答案 0 :(得分:0)

您不必等待fs.writeFile()完成,然后再尝试在下面的代码行中从文件中读取数据,因此您可能只会看到一个空文件,或者可能不会甚至在您尝试阅读它时仍被创建。

然后,您将同步逻辑与异步写入混合在一起,而无法传达成功或错误。如果这可以使用同步文件I / O(服务器在启动代码中不应该使用的同步文件I / O),则使其全部为同步文件I / O。

如果所有这些都需要异步进行,则需要完全重写,并且可以将其中的许多代码重构为几个共享函数。


对我来说,要在此功能中完成的所有工作还不是很清楚,但这是逻辑的简化版本,它使用完全异步的文件I / O并尝试使代码干燥一些。

const mkdirp = require('mkdirp');
const fs = require('fs');
const path = require('path');


bot.on('chat', function(username, message) {
    const time = clock.zonedDateTime('SYSTEM').toString();
    const rootDir = 'C:/Users/La Fam/Desktop/kekbot_rewritten(tm)/players/';
    const wordsDir = path.join(rootDir, username, 'lirstwords/lastwords');
    const wordsFile = path.join(wordsDir, "lastwords.txt");

    // do something useful when there's an error
    // perhaps chat back that an unexpected error was encountered
    function processError(err) {
        console.log(err);
    }

    // make sure the desired directory exists (all the pieces of it)
    mkdirp(wordsDir, function(err) {
        if (err) return processError(err);
        let data = 'sentat:' + time + ',<' + username + '>' + message;
        fs.writeFile(wordsFile, data, {encoding: 'utf8', flag: 'wx'}, function(err) {
            if (err) {
                // we expect an error here if the file already exists, the wx flag will prevent overwriting existing file
                // we do it this way to avoid race condition on checking if it exists and avoid extra system call
                if (err.code !== 'EEXIST') {
                    processError(err);
                }
            if (message.startsWith('!lastwords ') && cooldown === 1) {
                const lastwordperson = message.toString().split(" ")[1];
                const lastWordFile = path.join(rootDir, lastwordperson, '/lirstwords/lastwords/lastwords.txt');
                fs.readFile(lastWordFile, 'utf8', function(err, data) {
                    if (err) {
                        // treat file not found separately
                        if (err === 'ENOENT') {
                            bot.chat(" does not have any documents that include the user " + lastwordperson);
                        } else {
                            processError(err);
                        }
                    } else {
                        bot.chat(data);
                    }
                });
            }
        });
    });
});