Search code examples
javascriptnode.jssettimeoutsynchronous

How to execute functions synchronously to get the right output


I am making an application which reads a file and extracts the data line by line. Each line is then stored as an array element and that array is required as the final output.

const fs = require('fs');
const readline = require('readline');

var output_array=[];
const readInterface = readline.createInterface({
    input: fs.createReadStream(inp_file),
    console: false
});
readInterface.on('line', function(line) {
    //code for pushing lines into output_array after doing conditional formatting
}

callback (null, output_array);

With this I am getting an empty array. Though if I use 'setTimeout' then it's working fine

setTimeout(() => {
  callback (null, output_array);
}, 2000);

How can I execute this synchronously without having to use 'setTimeout'?


Solution

  • Make your callback from readline's close event handler. That way your callback will happen after all lines are read.

    readInterface.on('close', function(line) {
      callback (null, output_array);
    }