node.jsline-by-line

Not able to access value in nodejs code


I have following code in my nodejs function. Even if the IF condition is true, I am not getting values updated for stringResponse variable.

var fs = require('fs'), 
                byline = require('byline');
            var stream = fs.createReadStream('Solutionbank.csv');
            var stringResponse = "We found a similar issue.  ";
            stream = byline.createStream(stream);
            stream.on('data', function(line) {
              var csvLine = line.toString('utf8');
                  csvLine = csvLine.toLowerCase().trim();

              var msgText = subject.toLowerCase().trim();
              //console.log("email block",msgText);
              if(csvLine.indexOf(msgText) > -1) {
                var arr = line.toString('utf8').split(",");

                stringResponse = stringResponse + "Issue ID"+arr[0]+",Subject : "+arr[1]+", Resolution Comment:"+arr[2];
                console.log(stringResponse);

                }
            });

            console.log("stringResponse from email",stringResponse);

Solution

  • Line :

    console.log("stringResponse from email",stringResponse);

    Is outsite on('data') callback function, this line is called before setting the stringResponse variable. Put it at the end of the callback function (inside). Or in the other callback function called at the end of the stream :

    stream.on('data', function(line) {
      ...
      console.log("stringResponse from email",stringResponse); // show each append 
    });
    
      stream.on('end', function() {
      ...
      console.log("stringResponse from email",stringResponse); // show each append 
    });