how to import papaparse in javascript?

4.2k Views Asked by At

I installed papaparse using npm install papaparse in my createa folder. However, when I try to do import { Papa } from 'papaparse'; in index.js I get this error:

(node:6680) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/Users/y/createa/index.js:2
import { Papa } from 'papaparse';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:992:16)
    at Module._compile (internal/modules/cjs/loader.js:1040:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:941:32)
    at Function.Module._load (internal/modules/cjs/loader.js:782:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

I also tried const { Papa } = require("papaparse");:

const { Papa } = require("papaparse");

papa = Papa()
papa.parse("x.csv",{
    complete: parsedData => {
        let headerRow = parsedData.data.splice(0, 1)[0];
        let csvData = parsedData.data;
    }
})

This was the error I got:

/Users/y/createa/index.js:9
papa = Papa()
       ^

TypeError: Papa is not a function
    at Object.<anonymous> (/Users/y/createa/index.js:9:8)
    at Module._compile (internal/modules/cjs/loader.js:1076:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:941:32)
    at Function.Module._load (internal/modules/cjs/loader.js:782:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

How do I fix this so I can read a CSV file? Sorry I am very new to Javascript and I am so confused how this works. Thank you!

1

There are 1 best solutions below

0
On

hmmm I think you should you papaparse like that

const fs = require('fs');
const papa = require('papaparse');
const file = fs.createReadStream('challenge.csv');
var count = 0; // cache the running count
papa.parse(file, {
    worker: true, // Don't bog down the main thread if its a big file
    step: function(result) {
        // do stuff with result
    },
    complete: function(results, file) {
        console.log('parsing complete read', count, 'records.'); 
    }
});

I found a post about papaparse How can I read a local file with Papa Parse?