-1

This code is not giving output as I want.

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

async function readTwoColumnFile() {

    console.log('reading file');

    // (C) READ LINE-BY-LINE INTO ARRAY
    const reader = rl.createInterface({
      input: fs.createReadStream("index.js")
    });

    reader.on("line", (row) => {
      //some code
    });

    // (D) DONE - FULL ARRAY
    reader.on("close", async () => {
      // some code
      console.log('reading complete')
      res = 'Hello World!'
      return res
    });
}

async function run(){
    const res = await readTwoColumnFile()
    console.log('data' , res)
}

run()

Here the line console.log('data', res) is executing without res being initialized so when I run this code my output is coming

reading file
data undefined
reading complete

Instead of

reading file
reading complete
data Hello World!

So how can I wait for res to get executed after initilazation?

samsonmarandi
  • 61
  • 1
  • 6
  • Just because you made the callbacks async function, doesn't make this async code. Use the [Promises API](https://nodejs.org/api/readline.html#promises-api). – gre_gor Jan 04 '23 at 11:03

1 Answers1

2

You need to return a new Promise instance in readTwoColumnFile.

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

function readTwoColumnFile() {
  return new Promise((resolve, reject) => {
    console.log('reading file');

    // (C) READ LINE-BY-LINE INTO ARRAY
    const reader = rl.createInterface({
      input: fs.createReadStream("index.js")
    });

    reader.on("line", (row) => {
      //some code
    });

    reader.on('error', reject);

    // (D) DONE - FULL ARRAY
    reader.on("close", async () => {
      // some code
      console.log('reading complete')
      res = 'Hello World!'
      resolve(res);
    });
  });
    
}

async function run(){
    const res = await readTwoColumnFile()
    console.log('data' , res)
}

run()
Mehmet Baker
  • 1,055
  • 9
  • 23
  • Also, there is no event called `line`. You should use the `data` event (https://nodejs.org/api/stream.html#event-data) – martensi Jan 04 '23 at 11:13
  • 1
    You're welcome @samsonmarandi. @martensi, there is an event called `line` in Readline API (https://nodejs.org/dist/latest-v18.x/docs/api/readline.html#event-line). – Mehmet Baker Jan 04 '23 at 14:22