Papaparse返回空阵列

时间:2018-02-04 17:08:35

标签: node.js papaparse

// js function 
const generater = (csvFilePath) => {
  console.log(csvFilePath);
  Papa.parse(csvFilePath, {
    delimiter: ',',
    dynamicTyping: true,
    encoding: 'UTF-8',
    complete: function(results, file) {
      console.log(results);
      console.log(file);
    }
  });
};

// csv文件内容“demo.csv”

Column 1,Column 2,Column 3,Column 4
1-1,1-2,1-3,1-4
2-1,2-2,2-3,2-4
3-1,3-2,3-3,3-4
4,5,6,7

//该函数正在记录一个空数组,任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我只是想办法做到这一点。在nodejs中,papa-parse的工作方式不同。所以需要使用fs并提取本地文件内容然后解析字符串更合适。

// read the file and save content as a string
let content = fs.readFileSync(csvFilePath, { encoding: 'utf-8' });

// parse the string to object
let contentObject = parseData(content);
console.log(contentObject);

// function to parse the data synchronously of csv file
const parseData = (content) => {
  let data;
  return new Promise( (resolve) => {
    Papa.parse(content, {
      header: true,
      delimiter: ',',
      dynamicTyping: true,
      complete: (results) => {
        data = results.data;
      }
    });
    resolve(data);
  });
};