制作自己的“数据库"使用Node和FS [英] Making my own "database" using Node and FS

查看:68
本文介绍了制作自己的“数据库"使用Node和FS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I'm trying to make a database, couple of function snippets that read, write or create X.json files. The way I imagined it to be is a DB folder, then within that folder bunch of username folders, and there, a bunch of files, like account.json, level.json, and so on... So each folder would keep users data, now, this is the code I managed to write so far, and it works. 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 a bad idea. I don't understand why tho, as that seems like the only way to do it before I keep asking questions, I'd like to paste my code here:

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)是否存在是一种不好的做法呢?我想我可以对从readFile函数得到的错误做一些事情,并忽略fs.stat函数,但是只要readFile函数遇到一个不存在的文件夹,我的服务器就会崩溃.

I haven't written a general function that does this for me, because I figured that the code above is a mess right now. So, why is it a bad practice to check for the existence of the file (fs.stat) before writing/reading from them? I guess I could do something with the error I get from the readFile function and omit the fs.stat function, but whenever readFile function comes across a folder that doesn't exist, my server just crashes.

我对Node不太熟悉,因此上面的代码可能绝对是胡说八道.这就是为什么我在这里!

I'm not very experienced with Node, so the code above is probably absolute nonsense. That's why I'm here!

如果readFile遇到不存在的文件夹,如何使我的服务器不崩溃,而是通过socket.io发出找不到帐户"?如果我将发出代码的位置放在那里,服务器反正会崩溃.

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? If I put that emit code there, my server just crashes anyway.

我只会使用MongoDB之类的东西,但是我有大量的空闲时间,做这样的事情对我来说很有趣. >使用像mongo这样的数据库是否更安全,还是人们这样做是为了避免浪费时间编写自己的数据库?

I would just go with MongoDB or something, but I have a loooot of free time and doing stuff like this is very fun for me. > Is using a DB like mongo like more secure, or do people do it so they don't have to waste time writing their own DB?

感谢您的帮助!

推荐答案

但是问题是,在FS文档上,它说在读/写文件之前使用fs.stat检查文件是否存在是一个坏主意.我不明白为什么

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文档中提到了原因:

The reason is mentioned on the deprecated fs.exists docs:

不建议在调用fs.open(),fs.readFile()或fs.writeFile()之前使用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.


如果readFile遇到一个不存在的文件夹,如何使我的服务器不崩溃,而是通过socket.io发出找不到帐户"?

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块包装代码,也可以使用promises. Promise提供了不错的API来处理应用程序中的错误. Node.js v10.0.0为fs模块API引入了承诺包装的API .

You don't handle the errors properly. As an example you throw an error in your .readFile callback but your code leaves the error unhandled, that will "crash" your application. You could either wrap your code with a try/catch block or use promises. Promises provide nice APIs to handle errors in your application. Node.js v10.0.0 introduces promise-wrapped APIs for fs module APIs.

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一起使用:

You can also use the APIs with try/catch and await:

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
}

如果不是选择使用节点v10.0.0,则可以使用npm软件包,该软件包提供承诺包装的fs API,例如 fs-extra draxt :

If using node v10.0.0 is not an option you can use a npm package that provides promised-wrapped fs APIs like fs-extra or draxt:

// 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
});

这篇关于制作自己的“数据库"使用Node和FS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆