Fs.readFile возврат не определен - PullRequest
0 голосов
/ 28 февраля 2019

Ответ на мою проблему, вероятно, очевиден, но я не могу его найти.

Я действительно хочу прочитать файл json в приложении nodeJS.

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

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

Я пишу это, и я не понимаю, почему он возвращает undefined, я проверил файл Json и есть некоторые данные.

Ответы [ 4 ]

0 голосов
/ 28 февраля 2019

Начиная с узла v0.5.x, вы можете запросить JSON так же, как и файл JS.

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

В ES6:

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

А если вам нужна строка, просто используйте JSON.stringify(someObject)

0 голосов
/ 28 февраля 2019

Попробуйте следующее:

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

const accRead = JSON.parse(accounts())

/*Logging for visualization*/
console.log(accRead)
0 голосов
/ 28 февраля 2019

Вы можете создать обещание и использовать async / await для его достижения.

Предположим, у вас есть такая файловая структура:

  • accounts.json
  • index.js

В account.json у вас есть это:

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

Ваш файл index.js должен быть:

// 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();
0 голосов
/ 28 февраля 2019

Попробуйте следующее:

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

Как уже упоминалось в комментариях, вы также можете использовать синхронную версию функции: fs.readFileSync ..

Вы можете упаковать этотакже в асинхронной функции, например:

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
   }
}
...