title: Making my own "database" using Node and FS
body: <p>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:</p>
  
  <pre><code>socket.on('play', (data) =&gt; {
      fs.stat(`db/${data.username}/account.json`, (error, result) =&gt; {
        if(!error) {
          fs.readFile(`db/${data.username}/account.json`, (error, result) =&gt; {
            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'
          });
        }
      });
    });
  </code></pre>
  
  <p>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 <code>fs.stat</code> function, but whenever readFile function comes across a folder that doesn't exist, my server just crashes.</p>
  
  <p>I'm not very experienced with Node, so the code above is probably absolute nonsense. That's why I'm here!</p>
  
  <p>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.</p>
  
  <p>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? </p>
  
  <p>Thanks for your help!</p>