parsingJSON,同时读取文件

我正在尝试读取几个JSON文件并将其结果存储到一个数组中。 我有:

const files = ['file0.json', 'file1.json', 'file2.json', 'file3.json'] 

为了读取所有这些文件并创build文件内容的结果数组,我这样做:

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

这篇文章帮助我达到目的: asynchronous读取和cachingnodejs中的多个文件

我想知道的是如何在读取文件的中间步骤中调用JSON.parse() ,而不必map结果数组。 我想澄清一下read函数里面的callback参数究竟是用来做什么的,如果不是为了正确地调用readFile而传入的话。

那么,也许你应该在阅读步骤中移动JSON.parse

 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', function(err, data) { if (err) { return callback(err); } try { callback(JSON.parse(data)); } catch (rejection) { return callback(rejection); } }) } async.map(files, read, (err, results) => { if (err) throw err; console.log('results', results) }) 

我build议你阅读这篇文章 ,了解callback函数的含义。