使用Promises时如何在PapaParse中使用本地文件

时间:2019-06-28 06:54:41

标签: javascript promise papaparse

我正在尝试使用PapaParse解析本地文件,但控制台返回未定义。另外,如果我注释掉download:true,控制台将返回一个空数组。我将本地文件作为参数传递的方式是否存在问题,因为在异步代码Papa.parse('./Clean.csv',{})中有效

const parseData = (content) => {
        let data;
        return new Promise((resolve) => {
            Papa.parse(content, {
                header: true,
                download: true,
                delimiter: ',',
                dynamicTyping: true,
                complete: (results) => {
                    data = results.data;
                }
            });
            resolve(data);
        });
    };

    parseData('./Clean.csv')
        .then(results => console.log(results));

1 个答案:

答案 0 :(得分:0)

您可以将文件流传递给Papa Parse,这对于服务器端代码非常有用:

const Papa = require('papaparse');
const fs = require('fs');

const parseData = (content) => {
    const fileStream = fs.createReadStream(content);
    return new Promise((resolve) => {
        Papa.parse(fileStream, {
            header: true,
            delimiter: ',',
            dynamicTyping: true,
            complete: (results) => {
                resolve(results);
            }
        });
    });
};

parseData('./Clean.csv')
    .then(results => console.log(results));