Workaround the Node JS File System

Written by _Obbap | Published 2018/11/06
Tech Story Tags: javascript | nodejs | web-development | node | node-js-file-system

TLDRvia the TL;DR App

Hello, fellow members of the night’s watch. We will be looking at one of Node’s core API’s, the File System. I know we’ve been concerned with code splitting, bundle splitting, preloading and the never ending woes of the Internet Explorer, but we will be learning how Node interacts with our files and directories. This helps us handle images or assets on our server, store them properly, read the content of other files, write to files,etc.

We will be building a basic CRUD application using the file system. I think we can get started.

Our little folder structure should look like this:

Database-----(folder)crud.js------(file)

The ‘Database’ folder is going to contain a file, that will hold our Automobile business data. This data is going to comprise of the name of a car, and it’s price. It will be stored in JSON. Obviously, this cannot be done in production, and in order to ensure that no one thinks of it, i’m stating it unequivocally.

CREATE

Now, we will be creating our cars.json file, from our crud.js file. Firstly, we will need the file system module, and the path module.

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

Then, we will create the crud object and its base directory, which holds the path from the crud.js file to the database folder.

const crud = {};crud.baseDir = path.join(__dirname,'./database');

Now, we will add a create function, and our crud.js file should look like this:

The ‘create’ function, holds the name of the file we want to create, and the data we want to write to the file. So we open a new file in the path we defined in the base directory, and it takes whatever name we assign.

‘wx’ means we can write to the file, but the operation will fail if the file already exists. There are so many other operations we can attribute to the file.

If there are no errors, Node attributes an identifier or a file descriptor to the file. If this identifier is found, we can then write to the file.

We want our database to look like this:

[{name: '', price: ''},{name: '', price: ''}]

This is the reason, we push the data to the jsonArray variable, before sending it to the file.

We can go to the bottom of our page, and run this:

crud.create('cars',{'name': 'innoson','price':'$4000'});

//Then Obviously(in your console)node crud

All things being equal, this should create a cars.json file with the array inside it.

READ

Now, we should be able to read the data from the file we just created. Our read function should look like this:

This function goes to the base directory, which is the database folder and then reads the data from the file we pass into the function. The encoding format is UTF-8, and without errors, our data should get logged.

We can go to the bottom of our page and run this:

crud.read('cars');

UPDATE

Now, we can use fs.truncate() to change the content of the whole file, but we will use fs.appendFile() to append data to our file.

If we go to the bottom of the page, and run the update function

crud.update('cars',{name:'Tesla',price:'$10'})

We will have an output like this:

[{name: 'innoson',price:'#4000'}],{name: 'Tesla',price:'$10'}

which is not what we desire, we need the object to be in the array. To do this, i came up with a plan.

  • We will read the current content of the cars.json file
  • Then, we will append our updates
  • Then, we will truncate the file and replace.

With the emphasis on ‘Then’, we will need to use promises. We will make use of another Node API, util.

Go to the top of your crud.js file and include:

const { promisify } = require("util");

const readFile = promisify(fs.readFile);

So, the ‘readFile’ variable will return promises. Our new crud.update function should look like this:

So, we can create a new JSON file in the database folder, and test our update function.

crud.create('cars-updated',{name:'mercedes',price:'$400'})

crud.update('cars-updated',{name:'Toyota',price:'$550'})

The cars-updated.json file should have the desired format.

DELETE

To delete a file, we use the fs.unlink method. So our crud.delete function should look like this:

So, we can delete the cars.json file, since its no longer needed.

crud.delete('cars')

You can see the crud.js file here

Thank you very much for reading,if you liked it, please clap. if you have any questions or you need further clarification, you can leave a comment or a mail([email protected]).


Published by HackerNoon on 2018/11/06