javascript - 使用 Node 和 FS 制作我自己的 "database"

标签 javascript node.js fs

所以我正在尝试制作一个数据库,几个读取、写入或创建 X.json 文件的函数片段。我想象的方式是一个 DB 文件夹,然后在该文件夹中有一堆用户名文件夹,还有一堆文件,比如 account.json、level.json 等等……所以每个文件夹都会保留用户数据,现在,这是我到目前为止设法编写的代码,并且可以正常工作。 但问题是,在 FS 文档上,它说在读取/写入文件之前使用 fs.stat 检查文件是否存在是一个坏主意。我不明白为什么,因为在我继续提问之前这似乎是唯一的方法,我想在这里粘贴我的代码:

socket.on('play', (data) => {
    fs.stat(`db/${data.username}/account.json`, (error, result) => {
      if(!error) {
        fs.readFile(`db/${data.username}/account.json`, (error, result) => {
          if(error) {
            throw error;
          } else {
            const rawResult = JSON.parse(result);

            if(data.password == rawResult.password) {
              socket.emit('playResponse', {
                success: true,
                msg: 'Login Succesfull'
              });
            } else {
              socket.emit('playResponse', {
                success: false,
                msg: 'Wrong Password!'
              });
            }
          }
        });
      } else if(error.code == 'ENOENT') {
        socket.emit('playResponse', {
          success: false,
          msg: 'Account not found'
        });
      }
    });
  });

我还没有为我编写一个通用函数来执行此操作,因为我认为上面的代码现在一团糟。那么,为什么在写入/读取文件 (fs.stat) 之前检查文件 (fs.stat) 的存在是一种不好的做法?我想我可以对从 readFile 函数中得到的错误做一些事情并省略 fs.stat 函数,但是每当 readFile 函数遇到一个不存在的文件夹时,我的服务器就会崩溃。

我对 Node 不是很熟悉,所以上面的代码可能完全是胡说八道。这就是我来这里的原因!

如果 readFile 遇到一个不存在的文件夹,我怎样才能让我的服务器不崩溃,而是通过 socket.io 发出“未找到帐户”?如果我将那个发出代码放在那里,我的服务器无论如何都会崩溃。

我会选择 MongoDB 之类的东西,但我有很多空闲时间,做这样的事情对我来说非常有趣。 > 使用像 mongo 这样的数据库更安全,还是人们这样做是为了不必浪费时间编写自己的数据库?

感谢您的帮助!

最佳答案

But the problem is, on the FS docs, it says that using fs.stat to check for the existence of the file before reading / writing to it is bad idea. I don't understand why tho

原因在已弃用的 fs.exists 文档中提到:

Using fs.exists() to check for the existence of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file does not exist.


How can I make my server not crash if the readFile comes across a non existent folder, but instead just emit the "Account not Found" through socket.io?

您没有正确处理错误。例如,您在 .readFile 回调中抛出一个错误,但您的代码未处理该错误,这将使您的应用程序“崩溃”。您可以使用 try/catch block 包装您的代码或使用 promises。 Promise 提供了很好的 API 来处理应用程序中的错误。 Node.js v10.0.0 引入了 promise-wrapped APIs用于 fs 模块 API。

const fs = require('fs');
const fsPromises = fs.promises;
fsPromises.readFile(`db/${data.username}/account.json`).then(error => {
   // the file exists and readFile could read it successfully! 
   // you can throw an error and the next `catch` handle catches the error
}).catch(error => {
  // there was an error
});

您还可以将 API 与 try/catchawait 一起使用:

try {
  const content = await fsPromises.readFile(`db/${data.username}/account.json`);
  // the file exists and readFile could read it successfully!
} catch(error) {
 // handle the possible error
}

如果使用 Node v10.0.0 不是一个选项,您可以使用 npm 包,它提供 promise 包装的 fs API,如 fs-extradraxt :

// using draxt
const $ = require('draxt');
const File = $.File;

const file = new File(`db/${data.username}/account.json`);
file.read('utf8').then(contents => {
   // the file exists and readFile could read it successfully!
}).catch(error => {
  // handle the possible error
});

关于javascript - 使用 Node 和 FS 制作我自己的 "database",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52236967/

相关文章:

javascript - 返回除特定索引之外的数组索引

node.js - 保存到文件时出错错误: EMFILE: too many open files

templates - node.js 的模板引擎

node.js - 从 Electron 打包应用程序运行 Cli 命令

node.js - node-orm 同步到 Alter Tables(类似于 DataMapper.auto_upgrade)

javascript - 使用 Fs 模块 : Error: write after end 在 NodeJs 中上传文档

node.js - 尽管安装了npm,但Gatsby找不到fs

javascript - 在谷歌分析中跟踪第三方插件的加载时间

javascript - 当文本较少时,将文本垂直对齐到图像中间

javascript - 将 javascript 动画置于背景的最简单方法是什么?