0

I'm writing a function which parses a file for a regex pattern and returns the matches in an array. The code I have is as follows:

function parse_file(filename, regex) {
    var lineReader = require('readline').createInterface({
        input: require('fs').createReadStream(filename)
    });
    var result = []

    lineReader.on('line', function(line) {
        var matches
        var rx = regex

        while ((matches = rx.exec(line)) !== null) {
            result.push(matches[1]);
            console.log(result.toString()) // i see the result!
        }
    })
    console.log(result.toString()) // i don't see the result!
    return result;
}

var rx0 = /foo\s?\((.*?)\s?bar/g;
var results = parse_file(inFile, rx0) // empty

The regex works fine and seems to push the value into the 'result' array in the parse_file function, however when I return result, I get nothing back.

  • 1
    `lineReader.on('line'` is asynchronous operation. By the time when you return `result`, it'll be empty array. – Tushar Apr 12 '17 at 12:14
  • @Tushar I understand, im struggling to update my code to handle the async nature of the request –  Apr 12 '17 at 12:29

0 Answers0