0
const fs = require('fs')
const readline = require('readline')
const stream = require('stream')

const rl = readline.createInterface({
    input: fs.createReadStream('logs_out.txt')
})

var items = new Set()

// ASYNC FUNCTION READING LINE BY LINE

rl.on('line', function(line) {
   let log = JSON.parse(line)
    // ADDING ITEMS TO A SET TO GET UNIQUE ITEMS COUNT
   items.add(log.resource)
})

// PRINTING OUT THE SIZE OF THE SET
console.log(items.size)

Now the issue is, when I do this I always get undefined or 0 for the size of the set because the console.log(items.size) is executed even before all the line functions are executed.

How to fix this.

Thank You.

1 Answers1

0

As noted as a possible duplicate by @str, there's a superb answer already here on Stack Overflow for why you might be best off with just embracing the asynchronous approach: How do I return the response from an asynchronous call?.

For your specific problem, I suggest you just use the close event from readline.

The readline.Interface instance should be considered to be "finished" once the 'close' event is emitted.

In your example, you can use the following:

// PRINTING OUT THE SIZE OF THE SET
rl.on('close', function() {
    console.log(items.size)
}
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203