L.DZ
L.DZ

Reputation: 171

Fs.readFile return undefined

The answer to my problem is probably obvious but I can't find it.

I actually want to read a json file on a nodeJS app.

var accRead = fs.readFile(__dirname + '/accounts.JSON', { endoding: 'utf8' }, function(err, data) {
    if (err) throw err

    if (data) return JSON.parse(data)
})

I write this, and I don't understand why it return undefined, I have checked the Json file and there is some data.

Upvotes: 0

Views: 7254

Answers (4)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12552

As of node v0.5.x you can require your JSON just as you would require a JS file.

var someObject = require('./awesome_json.json')

In ES6:

import someObject from ('./awesome_json.json')

And if you need string just use JSON.stringify(someObject)

Upvotes: 1

Dave
Dave

Reputation: 2210

You can create a promise and use async/await to achieve it.

Let's suppose you have a file structure like this:

  • accounts.json
  • index.js

In accounts.json you have this:

[
    {
        "id": 1,
        "username": "test1",
        "password": "test1"
    },
    {
        "id": 2,
        "username": "test2",
        "password": "test2"
    },
    {
        "id": 3,
        "username": "test3",
        "password": "test3"
    }
]

Your index.js file should be:

// importing required modules
const fs = require('fs');
const path = require('path');

// building the file path location
const filePath = path.resolve(__dirname, 'accounts.json');

// creating a new function to use async / await syntax
const readFile = async () => {

    const fileContent = await new Promise((resolve, reject) => {
        return fs.readFile(filePath, { encoding: 'utf8' }, (err, data) => {
            if (err) {
                return reject(err);
            }
            return resolve(data);
        });
    });
    // printing the file content
    console.log(fileContent);
}

// calling the async function to get started with reading file etc.
readFile();

Upvotes: 4

iLuvLogix
iLuvLogix

Reputation: 6430

Try the follwing:

fs.readFile(__dirname + '/accounts.JSON', 'utf8', function read(err, dataJSON) {
    if (err) {
       // handle err
    }
    else {
      // use/process dataJSON
    }
})

As already mentioned in the comments, you could use the synchronous version of the function: fs.readFileSync as well..

You could pack this also in a async function like:

function readJSONfile() {
   fs.readFile(__dirname + '/accounts.JSON', 'utf8', function read(err, dataJSON) {
      if (err) {
         return false
      }
      else {
         return dataJSON
      }
  })
}

async function () {
   let promise1 = new Promise((resolve, reject) => {
       resolve(readJSONfile())
   });
   let result = await promise1; // wait till the promise resolves (*)
   if (result == false) {
     // handle err
   }
   else {
     // process/use data
   }
}

Upvotes: 1

Try the following:

const accounts = () => fs.readFileSync(__dirname + '/accounts.json', { endoding: 'utf8'})

const accRead = JSON.parse(accounts())

/*Logging for visualization*/
console.log(accRead)

Upvotes: 1

Related Questions