8

I have looked at multiple resources for this, however, none seem to be able to answer my question. I have a local JSON file in my React app called items.json. In that file, is a list of objects, which I want to be able to update. I have tried using fs however this apparently doesn't work in React, as I received this error:

Unhandled Rejection (TypeError): fs.readFileSync is not a function

What I am trying to do, is that when the code gets a new item, it looks through the JSON file to see if there is an existing object with a matching values in its name property. If there is, it increments that objects count property by 1, otherwise it creates a new object, and appends it to the list in the JSON file. This is the code that I have written to do that. The logic seems sound (although its not tested) but I can't figure out how to read/write the data.

let raw = fs.readFileSync("../database/items.json");
let itemList = JSON.parse(raw);
let found = false;
for (let item of itemList.averages) {
    if (item.name === this.state.data.item_name) {
        found = true;
        item.count += 1;
    }
}
if (!found) {
    let newItem = {
        name: this.state.data.item_name,
        count: 1,
    }
    itemList.averages.push(newItem);
}
let newRaw = JSON.stringify(itemList);
fs.writeFileSync("../database/items.json", newRaw);

The JSON file:

{
    "averages": [
        {
            "name": "Example",
            "count": 1,
        }
    ]
}
SirArchibald
  • 476
  • 2
  • 7
  • 23
  • 1
    You're in a browser. You can't write files on the file system, but you can prompt the user to download them. [Related](https://stackoverflow.com/questions/21012580/is-it-possible-to-write-data-to-file-using-only-javascript) – Adam Jenkins Jan 26 '21 at 15:05
  • Why don't you just import the json file? – Gh05d Jan 26 '21 at 15:09
  • @Gh05d I did that originally but as far as I know (which isn't far), imorted files are read only. I may be wrong – SirArchibald Jan 26 '21 at 15:12
  • Ok, another question. Why do you want to save it in a JSON file? Why not use something like localStorage or sessionStorage? – Gh05d Jan 26 '21 at 15:15
  • I just assumed JSON would be easiest as I know how it works, but I am open to learning how localStorage and sessionStorage works if its a better option – SirArchibald Jan 26 '21 at 15:21
  • The local storage is good for storing user specific info. If you need to store something several users (or instances of your app) should access, you need database. All depends on what's the purpose of the data. It is possible to use JSON files, if you have some back-end running or a setup with Jenkins jobs to write the files, but nothing client side only. – kbo Jan 26 '21 at 15:29
  • Does this answer your question? [Local file access with JavaScript](https://stackoverflow.com/questions/371875/local-file-access-with-javascript) – Heretic Monkey Jan 26 '21 at 15:32

3 Answers3

10

First of all, the browser itself doesn't have access to the filesystem, so you won't be able to achieve that using your react app. However, this can be achieved if you use Node.js(or any other FW) at the backend and create an API endpoint which can help you to write to the filesystem.

Secondly, if you wanted to only do things on the frontend side without creating an extra API just for saving the data in a JSON file which I think is not necessary in your case. You can use localstorage to save the data and ask the user to download a text file using this :

TextFile = () => {
    const element = document.createElement("a");
    const textFile = new Blob([[JSON.stringify('pass data from localStorage')], {type: 'text/plain'}); //pass data from localStorage API to blob
    element.href = URL.createObjectURL(textFile);
    element.download = "userFile.txt";
    document.body.appendChild(element); 
    element.click();
  }

Now, To use local storage API you can check here - https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

B45i
  • 2,368
  • 2
  • 23
  • 33
Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
3

reading and writing JSON file to local storage is quite simple with NodeJs, which means a tiny piece of backend API in express would help get this job done.

few piece of code that might help you. Assuming you JSON structure would be such as below;

{
    "name":"arif",
    "surname":"shariati"
}

Read JSON file;

// import * as fs from 'fs';
const fs = require('fs')
fs.readFile('./myFile.json', 'utf8', (err, jsonString) => {
    if (err) {
        return;
    }
    try {
        const customer = JSON.parse(jsonString);
} catch(err) {
        console.log('Error parsing JSON string:', err);
    }
})

customer contains your JSON, and values can be accessed by customer.name;

Write to JSON File

Let's say you have an update on your JSON object such as below;

const updatedJSON = {
    "name":"arif updated",
    "surname":"shariati updated"
}

Now you can write to your file. If file does not exist, it will create one. If already exists, it will overwrite.

fs.writeFile('./myFile.json', JSON.stringify(updatedJSON), (err) => {
    if (err) console.log('Error writing file:', err);
})
Babadzhanov
  • 486
  • 1
  • 6
  • 19
Shariati
  • 121
  • 9
2

Importing and reading from json can be like:

import data from ‘./data/data.json’;

then use .map() to iterate data.

for writing locally you can use some libraries like https://www.npmjs.com/package/write-json-file

Nafis
  • 1,020
  • 17
  • 36