我想读取几个JSON文件并将其结果存储到一个数组中。我有:解析JSON,同时读取文件
const files = ['file0.json', 'file1.json', 'file2.json', 'file3.json']
为了读取所有的人创造一个产生的文件内容的阵列,我这样做:
import { readFile } from 'fs'
import async from 'async'
const files = ['file0.json', 'file1.json', 'file2.json', 'file3.json']
function read(file, callback) {
readFile(file, 'utf8', callback)
}
async.map(files, read, (err, results) => {
if (err) throw err
// parse without needing to map over entire results array?
results = results.map(file => JSON.parse(file))
console.log('results', results)
})
这篇文章帮助我到达那里:Asynchronously reading and caching multiple files in nodejs
我想知道的是如何在读取文件的中间步骤中调用JSON.parse()
,而不是必须通过结果数组的map
。并且我想澄清一下在读取函数中究竟使用callback
参数,如果不是恰好为了正确调用readFile
而传入。
你可以像'readFile(file,'utf8')。然后(JSON.parse).then(回调)'吗? – dandavis
@dandavis让我们不要侮辱承诺尚未; –