最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to read and write to local JSON files from React.js? - Stack Overflow

programmeradmin2浏览0评论

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,
        }
    ]
}

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,
        }
    ]
}
Share Improve this question asked Jan 26, 2021 at 15:02 SirArchibaldSirArchibald 5163 gold badges8 silver badges28 bronze badges 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 – Adam Jenkins Commented Jan 26, 2021 at 15:05
  • Why don't you just import the json file? – Gh05d 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 – SirArchibald 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? – Gh05d 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 – SirArchibald Commented Jan 26, 2021 at 15:21
 |  Show 2 more comments

3 Answers 3

Reset to default 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

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

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

发布评论

评论列表(0)

  1. 暂无评论