csvToJson icon indicating copy to clipboard operation
csvToJson copied to clipboard

[BUG] TypeError: csvToJson.indexHeader is not a function

Open J-Siu opened this issue 2 years ago • 4 comments

Expected Behavior

Should not throw error.

Actual Behavior

$ node test.js raw/0*                                                                                                                                                          1 ↵
[ { a: 'e', b: 'f' } ]
/Users/js/code/private/csv2report/node_modules/convert-csv-to-json/index.js:42
  csvToJson.indexHeader(index);
            ^

TypeError: csvToJson.indexHeader is not a function
    at exports.indexHeader (/Users/js/code/private/csv2report/node_modules/convert-csv-to-json/index.js:42:13)
    at file:///Users/js/code/private/csv2report/test.js:6:4
    at ModuleJob.run (node:internal/modules/esm/module_job:192:25)
    at async DefaultModuleLoader.import (node:internal/modules/esm/loader:228:24)
    at async loadESM (node:internal/process/esm_loader:40:7)
    at async handleMainPromise (node:internal/modules/run_main:66:12)

Steps to Reproduce the Problem

  1. Prepare 2 or more csv files
  2. Save test.js
import csv from 'convert-csv-to-json'

for (const file of process.argv.slice(2)) {
	console.log(`===${file}===`)
	var json = csv
		.fieldDelimiter(',')
		.indexHeader(0)
		.supportQuotedField(true)
		.getJsonFromCsv(file)
	console.log(`===${file} JSON===`)
	console.log(json)
}
  1. Run following, replace csv files with your own
node test.js 01.csv 02.csv
  1. 1st file will always pass, then 2nd file will throw error

Specifications

  • Version:
    • "convert-csv-to-json": "^2.0.0"
    • Node.js v20.4.0

PS

Seems the issue arise from csvToJson.js:

Ln27: indexHeader(indexHeader) ...

Here `indexHeader` is a class function

Ln31: this.indexHeader = indexHeader;

After 1st time `indexHeader()` is called, `this.indexHeader` changed from a function to an integer.

J-Siu avatar Jul 16 '23 16:07 J-Siu

So happy to see this issue has already been reported. I am facing the same issue.

anandbhaskaran avatar Jul 18 '23 12:07 anandbhaskaran

So happy to see this issue has already been reported. I am facing the same issue.

Luckily indexHeader is not private. My workaround is assign the number directly and ignore the function. Small draw bask is you cannot chain it, and have to assign it before calling getJsonFromCsv() etc.

import csv from 'convert-csv-to-json'

# Assign indexHeader first
csv.indexHeader = 5
# Then call ...
var json = csv
	.fieldDelimiter(',')
	.supportQuotedField(true)
	.getJsonFromCsv(file)

J-Siu avatar Jul 18 '23 19:07 J-Siu