node-csvtojson icon indicating copy to clipboard operation
node-csvtojson copied to clipboard

When using readline module I am always getting empty arrays

Open derherbst opened this issue 6 years ago • 0 comments

I want to convert my csv file line by line to JSON and after that write it line by line to result.txt

Here is what I am doing

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

Unfortunately every time I am getting an empty array inside then(). But line exists! If I add noheader: true then the output is like this:

[
  {
    field1: 'firstName',
    field2: 'lastName',
    field3: 'email',
    field4: 'phoneNumber'
  }
]
[
  {
    field1: 'John',
    field2: 'Doe',
    field3: '[email protected]',
    field4: '0123456789'
  }
]
[
  {
    field1: 'Jane',
    field2: 'Doe',
    field3: '[email protected]',
    field4: '9876543210'
  }
]

But I am 100% sure that header exists and I don't need noheader config. Is there any way to use fromString inside readline event?

derherbst avatar Dec 02 '19 08:12 derherbst