Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read csv file in Angular-4 assets

I am new to angular-4 and I want to read a csv file from angular-4 assets directory, file size 5mb and I dont't want to read this file from django back-end server because this file is to show only demo graphs and I don't need to send 5mb extra request to server, thanks currently I follow this stack overflow question

Files Reading

private fs = require('fs');

readCsvData () {
    let allText = this.fs.readFileSync('assets/demo-Results.csv', 'utf8');
    console.log(allText)
    // this.extractData(allText);
}

Error is :

ShowDemoResultsComponent.html:17 ERROR TypeError: this.fs.readFileSync is not a function at ShowDemoResultsComponent.webpackJsonp.../../../../../src/app/show-demo-results/show-demo-results.component.ts.ShowDemoResultsComponent.readCsvData (show-demo-results.component.ts:119) at Object.eval [as handleEvent] (ShowDemoResultsComponent.html:17) at handleEvent (core.es5.js:12023) at callWithDebugContext (core.es5.js:13493) at Object.debugHandleEvent [as handleEvent] (core.es5.js:13081) at dispatchEvent (core.es5.js:8615) at core.es5.js:9226 at HTMLButtonElement. (platform-browser.es5.js:2651) at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425) at Object.onInvokeTask (core.es5.js:3881)

like image 266
Nazir Ahmed Avatar asked Dec 04 '22 20:12

Nazir Ahmed


1 Answers

In case you use the new HttpClient class (@angular/common/http), then you will have to set the responseType to 'text', otherwise the HttpClient class would try to interpret the content as json and raise a SyntaxError...

e.g.:
this.http.get('assets/file.csv', {responseType: 'text'})
    .subscribe(
        data => {
            console.log(data);
        },
        error => {
            console.log(error);
        }
    );
like image 113
Andi Avatar answered Dec 06 '22 11:12

Andi