11

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,
        }
    ]
}
7
  • 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 Commented Jan 26, 2021 at 15:05
  • Why don't you just import the json file? Commented Jan 26, 2021 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 Commented Jan 26, 2021 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? Commented Jan 26, 2021 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 Commented Jan 26, 2021 at 15:21

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

4 Comments

nice! we can also use input type = file to allow the user to choose a file name
I get an error : TS2322: Type '[string]' is not assignable to type 'BlobPart'. Type '[string]' is not assignable to type 'ArrayBuffer'. @B45i
Copied from here without giving credit: stackoverflow.com/a/53449590/4743466
@ErikVesterlund this is the normal way of writing and reading large JSON or any data in Javascript. You can check out several post and you will find similar post that doesn't things are copied.
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);
})

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.