require function that uses for await loop

40 Views Asked by At

I have a file where I defined a function that uses a for await loop for reading a file:

// updater.js
const lineReader = require('readline').createInterface({
  input: fs.createReadStream('./my-file.txt'),
})

const updateFile = async () => {
  // stuff..
  for await (const line of lineReader) {
    // do something...
  }
}

module.exports = {
  updateFile,
}

The function simply reads a file line by line, looking for a certain pattern that identifies a line that has to be updated; and saves line by line to another file with updates in place;

the thing is that this works correctly if at the end of the file I add updateFile() and execute it with node updater.js

What I'd like to do, is to require updater.js from another script:

// main.js
const updater = require('./updater')

const start = async () => {
  console.log('start')
  // do stuff...
  await updater.updateFile()

  console.log('end')
}

start()

ok so this is not working since it reaches the first console.log, it enters the updateFile method, it executes correctly until the for await loop, then the script ends, without throwing any error... I'm not really understanding this behavior, if someone has some clue I would be grateful...

0

There are 0 best solutions below