I am trying to take a csv file and convert it to a json using csvtojson. I keep getting a syntax error please help
const csvfilepath = require("../csvfiles/usethis.csv");
const csv = require('csvtojson');
router.post('/upload', (req,res) => {
csv()
.fromFile(csvfilepath)
.then((jsonObj)=>{
console.log(jsonObj)
})
})
My usethis.csv looks like this
Date,Time,CoreUsage ,TotalCPU ,MemoryClock
13.10.2021,53:54.4,13.6,13.6,1796.6
13.10.2021,53:56.5,12.7,12.7,1796.6
13.10.2021,53:58.5,21.3,21.3,1796.6
13.10.2021,54:00.5,11.2,11.2,1796.6
13.10.2021,54:02.6,5.5,5.5,1796.6
13.10.2021,54:04.6,13.1,13.1,1796.6
13.10.2021,54:06.7,14.6,14.6,1796.6
13.10.2021,54:08.7,16.9,16.9,1796.6
This is the error I keep getting
13.10.2021,53:54.4,13.6,13.6,1796.6
^^^^^
Syntax Error: Unexpected number
at wrapSafe (internal/modules/cjs/loader.js:915:16)
at Module._compile (internal/modules/cjs/loader.js:963:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module. Require (internal/modules/cjs/loader.js:887:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/mnt/c/users/blake/desktop/Fullmern/routes/benchmark.js:12:21)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module. Load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module. Require (internal/modules/cjs/loader.js:887:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/mnt/c/users/blake/desktop/Fullmern/server.js:19:15)
at Module._compile (internal/modules/cjs/loader.js:999:30)
[nodemon] app crashed - waiting for file changes before starting...
Thank you
CodePudding user response:
Try using double quotes on each value
Date,Time,CoreUsage,TotalCPU,MemoryClock
"13.10.2021","53:54.4","13.6","13.6","1796.6"
"13.10.2021","53:56.5","12.7","12.7","1796.6"
CodePudding user response:
Try replace
Date,Time,CoreUsage ,TotalCPU ,MemoryClock
with
Date,Time,CoreUsage,TotalCPU,MemoryClock //remove extra space
CodePudding user response:
You can't require()
a .CSV
file like you are trying to do here:
const csvfilepath = require("../csvfiles/usethis.csv");
Require knows how to do two things:
- Load and run a file of Javascript.
- Read and parse a .JSON file (if any only if, the file has a
.json
file extension).
So, require()
is trying to parse your CSV as Javascript and immediately runs into a Javascript syntax error because .CSV formatted data is not valid Javascript (no surprise there).
If you want to read a .CSV file into memory, then use fs.readFileSync()
or fs.promises.readFile()
(depending upon whether you want a synchronous or asynchronous operation).
If you want to read and parse the .CSV file, then use one of the many modules on NPM for reading/parsing CSV files.