【发布时间】:2016-06-04 13:34:24
【问题描述】:
我正在尝试读取一些 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。我想澄清一下 read 函数中的 callback 参数到底是做什么用的,如果不是为了正确调用 readFile 而传入的话。
【问题讨论】:
-
你能做类似
readFile(file, 'utf8').then(JSON.parse).then(callback)的事情吗? -
@dandavis 让我们不要用承诺侮辱 ts ;)
标签: javascript json node.js asynchronous readfile