Write to a Text or Json File in React With Node

Write to a text or JSON file in react with node

To write into the file use the fs module in Node JS:

To run install:

npm install --save cors
npm install --save express
npm install --save body-parser
npm install --save-dev morgan

Here is the index.js file:


// index.js
const cors = require('cors');
const express = require('express');
const morgan = require('morgan');
const fs = require('fs');
const bodyParser = require('body-parser');
const promisify = require('util').promisify;

const app = express();
const port = 5000;
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(cors());
app.options('*', cors());

const writeFilePromise = promisify(fs.writeFile);

WriteTextToFileAsync = async (contentToWrite) => {

try {
// FIXME: give your own path, this is just a dummy path
const path = 'C:\\foo.txt';
await writeFilePromise(contentToWrite, path);
} catch(err) {
throw new Error(`Could not write file because of {err}`);
}
}



// Default route
app.get('/', (req, res) => res.status(200).send({ message : 'Hello world' }));


// Write route
app.use('/write', async (req, res, next) => {

try {
//FIXME: Simply write the entire request body for now
const fileContent = req.body;
await WriteTextToFileAsync(fileContent);
return res.status(200).send( { message: 'File written successfully!' });
} catch (err) {
throw new Error(`Could not write file because of {err}`);
}
});

// Not-found route
app.use((req, res, next) => {
res.status(404).send({ message: 'Could not find the specified route you requested!' });
});

app.listen(port, () => console.log(`Server up and running and listening for incoming requests on port ${port}!`));

Write / add data in JSON file using Node.js

If this JSON file won't become too big over time, you should try:

  1. Create a JavaScript object with the table array in it

    var obj = {
    table: []
    };
  2. Add some data to it, for example:

    obj.table.push({id: 1, square:2});
  3. Convert it from an object to a string with JSON.stringify

    var json = JSON.stringify(obj);
  4. Use fs to write the file to disk

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
  5. If you want to append it, read the JSON file and convert it back to an object

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
    if (err){
    console.log(err);
    } else {
    obj = JSON.parse(data); //now it an object
    obj.table.push({id: 2, square:3}); //add some data
    json = JSON.stringify(obj); //convert it back to json
    fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
    }});

This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.

UPDATE:

Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback).
With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.

React:write to json file or export/download [no server]

I had a blob containing data and I had found a solution on stackoverflow and manipulated a bit, and succeded to download as a xlsx file. I am adding my code below, it might help you, too.

const blob =  await res.blob(); // blob just as yours
const href = await URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = href;
link.download = "file.xlsx";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

EDIT: You can use the function below, but be sure to switch out fileName and myData from this.state to something that will work in your application.

const downloadFile = () => {
const { myData } = this.state; // I am assuming that "this.state.myData"
// is an object and I wrote it to file as
// json

// create file in browser
const fileName = "my-file";
const json = JSON.stringify(myData, null, 2);
const blob = new Blob([json], { type: "application/json" });
const href = URL.createObjectURL(blob);

// create "a" HTLM element with href to file
const link = document.createElement("a");
link.href = href;
link.download = fileName + ".json";
document.body.appendChild(link);
link.click();

// clean up "a" element & remove ObjectURL
document.body.removeChild(link);
URL.revokeObjectURL(href);
}

More documentation for URL.createObjectURL is available on MDN. It's critical to release the object with URL.revokeObjectURL to prevent a memory leak. In the function above, since we've already downloaded the file, we can immediately revoke the object.

Each time you call createObjectURL(), a new object URL is created, even if you've already created one for the same object. Each of these must be released by calling URL.revokeObjectURL() when you no longer need them.

Browsers will release object URLs automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so.



Related Topics



Leave a reply



Submit