0

I was using csv-parse succesfully in a Vue project. The code looks like this:

import * as csvParse from 'csv-parse';
const parse = require('csv-parse')

const parseOptions: csvParse.Options = {
    //options here...
};

var parser: csvParse.Parser = csvParse(parseOptions, function(data, err) {
    console.log(data);
}) as csvParse.Parser;

const parseCallback:csvParse.Callback = (err: Error|undefined, records: any, info: csvParse.Info) => 
{
    //code to run after parse...
};
parse(csvText, parseOptions, parseCallback);

We switched to Angular 8 and the same code started raising this error:

index.js:43 Uncaught ReferenceError: global is not defined
    at Object../node_modules/buffer/index.js (index.js:43)
    at __webpack_require__ (bootstrap:79)
    at Object../node_modules/safe-buffer/index.js (index.js:2)
    at __webpack_require__ (bootstrap:79)
    at Object../node_modules/readable-stream/lib/_stream_readable.js (_stream_readable.js:55)
    at __webpack_require__ (bootstrap:79)
    at Object../node_modules/readable-stream/readable-browser.js (readable-browser.js:1)
    at __webpack_require__ (bootstrap:79)
    at Object../node_modules/stream-browserify/index.js (index.js:28)
    at __webpack_require__ (bootstrap:79)

I added

declare function require(path: string): any;

to handle require in typescript. I also tried removing the require. I get the same error.

How can I fix this? Thanks.

1 Answers1

0

After installing the csv-parse you can change the polyfills.ts and add this line of code:

(window as any)['global'] = window;

Then in your app.module.ts, try to import the CSV module:

@NgModule({
    declarations: [
        ...
    ],
    imports: [
        ...
        CSVModule.forRoot(),
        ...
    ],
    exports: [
        ...
    ],
    providers: [
       ...    ],
    bootstrap: [AppComponent]
})

Here's a related SO post.

EDITED

Regarding the error you encoutered, try to add this inside the polyfills.ts:

// @ts-ignore
window.Buffer = window.Buffer || require('buffer').Buffer;

This should solve your problem.

jess
  • 2,376
  • 1
  • 7
  • 23
  • After adding the polyfill I get this error: util.js:103 Uncaught ReferenceError: Buffer is not defined at Object../node_modules/core-util-is/lib/util.js (util.js:103) – Ionut Breaz Oct 08 '19 at 07:42
  • If I add the polyfill for Buffer I get an error about process, then about slice... – Ionut Breaz Oct 08 '19 at 07:52
  • Then I will recommend to use [`angular-csv-prser`](https://www.npmjs.com/package/angular-csv-parser). – jess Oct 08 '19 at 08:14
  • Thank you. I was also looking for an alternative. I found https://www.npmjs.com/package/papaparse – Ionut Breaz Oct 08 '19 at 08:18