tnoel999888
tnoel999888

Reputation: 654

How to write to text file in React

I have a text file called certs-list with a list of domain names in the format:

www.google.com
www.facebook.com
www.youtube.com

This file is then read in a script which generates a JSON file with information about these domain's SSL certificates.
This JSON file is then read by my NodeJS back-end in the GET API and the information is displayed in a table in my React app.

I want to be able to click a button in my React app to delete a row from my table and delete the corresponding entry from certs-list so that it is no longer displayed in my table.

For example deleting the Youtube row would update certs-list to:

www.google.com
www.facebook.com

and then the next time the JSON is built there would only be entries for Google and Facebook.

I tried using fs.writeFileSync but discovered that React does not have this function. Is there another function I can use to write to (delete entry from) certs-list?

Upvotes: 1

Views: 18407

Answers (2)

Khabir
Khabir

Reputation: 5854

You cannot access file from React as React runs in a browser. But you can access file from nodejs. As you said that you use fs.writeFileSync where fs is the node module to access file system. You need to include required module using require('fs'). Here is the example:

const fs = require('fs');
const jsonData= {"name":"John", "age":30, "car":null};
const jsonString = JSON.stringify(jsonData);

fs.writeFile("./foo.json", jsonString, 'utf8', function (err) {
    if (err) {
        return console.log(err);
    }
    console.log("file saved!");
}); 

Upvotes: 1

Hasnain Bukhari
Hasnain Bukhari

Reputation: 468

If you need to read or write to the file then you can use above function that you have mention. There might be you are missing package file that refer to file writer or missing in that component.

There is another NPM package that you can use to read and write to file. Here is the link given below

https://www.npmjs.com/package/write-file-p

Upvotes: 1

Related Questions