csv - Using Typescript unable to assign a value to the Class level variable inside fs.createReadStream -
i new typescript , have scenario in need read data csv file , assign values class level map<>
variable. following code trying out facing below issues:-
a) vs code intellisence doesn't prompt me name of class level map<>
variable when try this.nameofmapvariable
inside fs.createreadstream
function
b) if ignore intellisence thingy , try , write code assigning value, @ runtime error:-
cannot read property set of undefined
code snippet of csvhelper.ts
file:-
import * csvparse 'csv-parser'; import fs = require('fs'); var parse = csvparse.parser; export class csvhelper { public testspecificdata = new map<string, string>(); public fetchtestspecificdata(clsname: string, mthdname: string): map<string, string> { fs.createreadstream('../testdata/testspecificdata.csv').pipe(csvparse()).on('data', function (data) { if (data.testclass == clsname && data.testmethod == mthdname) this.testspecificdata.set(data.key.tostring(), data.value.tostring()); } ) return this.testspecificdata; } }
thats because defining function, called event data
. keyword this
gets new context call, testspecificdata
indeed not exist.
you can try lambda expression, this
stays in expected context:
fs.createreadstream('../testdatatestspecificdata.csv') .pipe(csvparse()) .on('data', (data) => { if (data.testclass == clsname && data.testmethod == mthdname) { this.testspecificdata.set(data.key.tostring(), data.value.tostring()); } });
Comments
Post a Comment