0

I'm trying to read in a csv file line by line, I've got the line by line reader working but now I need to put it in a callback to ensure its finished reading before I move on to process the data. However, I think I've misunderstood how to use a callback to do so because the array I'm trying to fill is still empty.

var data = [],
 power = null,
 wattH = null,
 watts = null,
 maxTemp = null,
 averageTemp = null,
 maxCurrent = null,
 maxPower = null,
 totalTime = null;

var lineReader = require('readline').createInterface({
 input: require('fs').createReadStream(__dirname + '/logs/MOCK_DATA.csv')
});

function readlines() {
 getLines(function(lines) {
  data = lines;
 });
}

function getLines(callback) {
 var out = [];
 lineReader.on('line', function(line) {
  out.push(line);
 });
 callback(out);
}

readlines();
console.log(data);

Any help would be greatly appreciated :)

EDIT: The following worked

function readlines(callback) {
 var out = [];
 lineReader.on('line',callback, function(line) {
  out.push(line);
 });
 callback(out);
}

readlines(function(result){
 console.log(result);
});
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – str Sep 02 '17 at 17:03
  • It might be a duplicate but I looked at other posts first and only created one of my own because I didn't understand the others. It would really help me to see a specific example for my problem. – Henry Penton Sep 02 '17 at 17:17
  • Maybe this answers helps then: https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron It is specific to your problem. Does this help? – str Sep 02 '17 at 17:24
  • That did help, thank you! :) – Henry Penton Sep 02 '17 at 17:44

0 Answers0