5

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)

Sébastien
  • 11,860
  • 11
  • 58
  • 78
Nazir Ahmed
  • 615
  • 4
  • 14
  • 29
  • Possible duplicate of [Angular - Read a file and parse its content](https://stackoverflow.com/questions/47581687/angular-read-a-file-and-parse-its-content) – Aravind Dec 22 '17 at 07:31
  • Its not, In your mention reference, they read file from event that is bind with file upload btn but in my case file is not uploaded by upload btn, I just want to read file from assets. for example ` let fileReader = new FileReader(); fileReader.read('filepath', 'r')` kind of thing. – Nazir Ahmed Dec 22 '17 at 07:44

2 Answers2

14

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);
        }
    );
Andi
  • 156
  • 1
  • 3
4

I finally find a answer Here is how I done it:

csvUrl = 'assets/demo-Results.csv';
readCsvData () {
      this.http.get(this.csvUrl)
        .subscribe(
          data => {
            console.log(data.text())
          },
          err => {
            console.log(err)
          });
  }
Nazir Ahmed
  • 615
  • 4
  • 14
  • 29