I have stored CSV files within my application. I want to convert it to an array of objects. I'm using csv-parse. https://www.npmjs.com/package/csv-parse
error message for just requiring the csv file
error:
Ingredient #, Ingredient Description, Cycle Count ^
SyntaxError: Invalid or unexpected token
const parse = require('csv-parse/lib/sync');
const assert = require('assert');
const router = require('express').Router();
const count = require("./csv/IngCountCycle.csv");
router.get('/', function () {
console.log("HI");
const input = `
"key_1","key_2"
"value 1","value 2"
`;
const records = parse(input, {
columns: true,
skip_empty_lines: true
});
console.log(records)
//output ([{key_1: 'value 1', key_2: 'value 2'}])
});
module.exports = router;
test.csv
Ingredient #, Ingredient Description, Cycle Count
1,GUACAMOLE,Annually,
2,GUACAMOLE,Period,
3,GUACAMOLE,Weekly,
4,GUACAMOLE,Custom
testParse.js
const parse = require('csv-parse/lib/sync');
const assert = require('assert');
const router = require('express').Router();
const count = require("./csv/IngCountCycle.csv");
router.get('/', function () {
const input = count;
const records = parse(input, {
columns: true,
skip_empty_lines: true
});
console.log(records)
});
module.exports = router;
-
you can't just require a csv in plain vanilla node, can you?Jaromanda X– Jaromanda X2019年04月29日 21:37:36 +00:00Commented Apr 29, 2019 at 21:37
-
would I have to convert it?KamSami– KamSami2019年04月29日 21:42:52 +00:00Commented Apr 29, 2019 at 21:42
2 Answers 2
You have an extra , (comma) on lines 1, 2 and 3 but not 4. Your header line has 3 commas. You either need to clean the data before using it or account for this discrepancy in your data with some code.
Comments
Seems like CSVParse is not being able to interpret your row delimiter. Could you confirm that you are using one of the supported options for row delimiter, as specified in the docs (check option record_delimiter)?
Then, try to be explicit about which delimiter you are using, like below:
const records = parse(input, {
columns: true,
skip_empty_lines: true,
record_delimiter: "\n"
});