2016-02-22 73 views
2

我想读取几个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而传入。

+0

你可以像'readFile(file,'utf8')。然后(JSON.parse).then(回调)'吗? – dandavis

+0

@dandavis让我们不要侮辱承诺尚未; –

回答

1

嗯,也许你应该阅读一步一个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) 
}) 

我建议你阅读this article理解回调函数的含义。

+0

这确实解析了JSON,但有几个问题。实际结果以'async.map'回调中的参数'err'结束,'result'参数未定义。 另外,只有第一个文件以'results'结尾。如果我在'try'中添加'console.log(JSON.parse(data))',它会在打印第一个文件的内容之后从'async.map'打印结果,然后打印内容剩余的文件。 –