Node JS从文件加载JSON数组

use*_*793 4 javascript json node.js

一个json文件已经创建了漂亮的打印

[
  {
    "name": "c",
    "content": 3,
    "_prototype": "item"
  },
  {
    "name": "d",
    "content": 4,
    "_prototype": "item"
  }
]
Run Code Online (Sandbox Code Playgroud)

我可以用那个读取文件

var fs = require('fs');
var arrayPath = './array.json';

function fsReadFileSynchToArray (filePath) {
    var data = JSON.parse(fs.readFileSync(filePath));
    console.log(data);
    return data;
}

var test  = arr.loadFile(arrayPath);
console.log(test);
Run Code Online (Sandbox Code Playgroud)

但输出顺序相反

[]
[ { name: 'c', content: 3, _prototype: 'item' },
  { name: 'd', content: 4, _prototype: 'item' },]
Run Code Online (Sandbox Code Playgroud)

显然第二个输出显示为第一个.我实际上使用了同步文件读取来避免这种空数据.有没有办法真正确保JSON文件在继续之前完全读入数组?

[update] arr是一个使用的模块

function loadFile(filePath){
    var arrLines = [];
    fs.stat(filePath, function(err, stat) {
        if(err == null) {
            arrLines = fsReadFileSynchToArray(filePath);
        } else if(err.code == 'ENOENT') {
            console.log('error: loading file ' + filePath + ' not found');
        } else {
            console.log('error: loading file', err.code);
        }
    });
    return arrLines;
}
Run Code Online (Sandbox Code Playgroud)

返回值

jes*_*lla 15

只要文件位于项目文件夹(即配置文件,即)中,您就可以直接在NodeJS中同步加载它.

var test = require('./array.json');
Run Code Online (Sandbox Code Playgroud)

然后,内容将在下一个执行的句子中加载到您的变量中.

您可以尝试console.log它,它将打印:

[ { name: 'c', content: '3', _prototype: 'item' },
  { name: 'd', content: '4', _prototype: 'item' } ]
Run Code Online (Sandbox Code Playgroud)

正好按文件的顺序排列.


Que*_*tin 5

fs.stat 是异步的,所以你的函数是异步的。

你想要fs.fstatSync


t.n*_*ese 5

不建议在加载之前测试文件是否存在,这也是不推荐使用的原因fs.exists

不建议在调用或之前使用它fs.exists()来检查文件是否存在。这样做会引入竞争条件,因为其他进程可能会更改两次调用之间的文件状态。相反,用户代码应该直接打开/读取/写入文件,并处理文件不存在时引发的错误。fs.open()fs.readFile()fs.writeFile()

您使用的方式fs.stats只是与已弃用的方式等效fs.exists.

因此,您应该始终假设该文件在读取时不存在。

对于同步调用,您应该编写:

var data;

try {
   data = JSON.parse(fs.readFileSync(filePath));
} catch ( err ) {
   // handle your file not found (or other error) here
}
Run Code Online (Sandbox Code Playgroud)

或者

var data;

try {
   data = require('./array.json');
} catch ( err ) {
   // handle your file not found (or other error) here
}
Run Code Online (Sandbox Code Playgroud)

如果您以异步方式执行此操作,则检查回调函数的错误参数,以处理文件不存在的情况:

fs.readFile(filePath, (err, fileContent) => {
    var data;
    if( err ) {
      // handle your file not found (or other error) here
    } else {
      data = JSON.parse(fileContent);
    }
})
Run Code Online (Sandbox Code Playgroud)