Search code examples
node.jsexpresspathfs

Using fs read file I want to the json data in variable to pass to the nodejs


I am trying to use fs.readFile in my nodejs project. I want to read the file from a different location in the computer system and read it. After reading I want to store that JSON data into the object and access it into my project. Can anyone please help me with this I am stuck with a problem for a long time.

fs = require('fs');
path = require('path');
const location = path.join('/users/', 'hello.json');
let rawdata = fs.readFile(location, {encoding: 'utf-8'}, function(err, data){
let Issuedata = data;
});

Solution

  • You try this

    const {readFile} = require('fs/promises'); // using fs-promises
    const path = require('path');
    const file = path.join("/users/", "hello.json");
    const dataObj = {}; // object you intend to use
    
    readFile(file, {encoding: 'utf-8'}).then((result) => {
    
    if(!dataObj[result]) {
      dataObj[result] = JSON.parse(result);
      }
    });
    
    console.log(dataObj) // result
    

    The JSON file is read first, the result gotten from the readFile function is appended to the dataObj object. Hope it can help you or steer you in the right direction