csvtojson模块始终返回空数组

时间:2019-12-01 20:07:57

标签: javascript node.js csvtojson

我正在使用node-csvtojson模块将我的csv文件逐行转换为JSON,然后将其逐行写入result.txt

这是我的代码:

import fs from 'fs';
import path from 'path';
import readline from 'readline';
import csvToJson from 'csvtojson';

const csvFilePath = path.join(__dirname, '/example.csv');
const fileOutputPath = path.join(__dirname, '/result.txt');

const input = fs.createReadStream(csvFilePath);

const output = fs.createWriteStream(fileOutputPath, {
  flags: 'w',
});

const inputFileLine = readline.createInterface({
  input,
  terminal: false,
  output,
})

inputFileLine.on('line', (line) => {

  const result = csvToJson()
    .fromString(line)
    .then((csvRow) => {
      console.log(csvRow);
      return csvRow;
    })

  console.log(result);

  // output.write(result);
})

不幸的是,每次我在then()中都得到一个空数组时。但是line存在! 如果我添加noheader:true(默认情况下为false),则输出如下所示:

[
  {
    field1: 'firstName',
    field2: 'lastName',
    field3: 'email',
    field4: 'phoneNumber'
  }
]
[
  {
    field1: 'John',
    field2: 'Doe',
    field3: 'john@doe.com',
    field4: '0123456789'
  }
]
[
  {
    field1: 'Jane',
    field2: 'Doe',
    field3: 'jane@doe.com',
    field4: '9876543210'
  }
]

但是我100%确信头文件存在并且不需要noheader配置。 我在哪里错了?

0 个答案:

没有答案