导入JSON文件后无法在fs.readFile外部访问转换后的数组怎么解决
问题原因与修复方案
问题根源
你调用的fs.readFile是Node.js内置的异步IO接口,代码执行时不会等待文件读取完成、回调函数执行,就会直接运行回调外的打印、遍历逻辑。此时results还没有被赋值,仍然是初始化的空数组,所以会出现长度为0、循环不执行的情况。
修复方案
方案1:将results操作逻辑移入回调
把所有需要用到读取结果的逻辑,都放到readFile的回调函数内部执行,保证只有文件读取完成后才会执行相关逻辑:
'use strict'; const fs = require('fs'); fs.readFile('myfile.json', (err, data) => { if (err) throw err; const results = JSON.parse(data); console.log('results length:', results.length); // 注意不要用for...in遍历数组,改用for...of获取数组元素 for (const r of results) { console.log('res', r); console.log(r.configuration.value); } });
方案2:使用同步读取API
如果是简单脚本场景,可以改用同步读取接口fs.readFileSync,代码会阻塞等待文件读取完成后再往下执行:
'use strict'; const fs = require('fs'); // 同步读取文件,直接返回文件内容 const data = fs.readFileSync('myfile.json'); const results = JSON.parse(data); console.log('results length:', results.length); for (const r of results) { console.log('res', r); console.log(r.configuration.value); }
方案3:Promise + async/await写法(推荐)
Node.js v10以上版本支持fs.promises接口,配合async/await可以写出更易维护的异步代码,避免回调嵌套:
'use strict'; const fs = require('fs/promises'); async function readJsonFile() { try { const data = await fs.readFile('myfile.json'); const results = JSON.parse(data); console.log('results length:', results.length); for (const r of results) { console.log('res', r); console.log(r.configuration.value); } } catch (err) { throw err; } } readJsonFile();
额外注意
你的原代码中使用for (r in results)遍历数组,for...in遍历出来的是数组的索引字符串,不是数组本身的元素,所以即使拿到了正确的results,也无法通过r.configuration.value获取到对应属性,需要改为for...of遍历获取数组元素,或者通过results[r].configuration.value取值。
内容的提问来源于stack exchange,提问作者blnks
相关产品推荐
相关产品推荐

