0

const express = require('express')
const fs = require('fs')
const router = new express.Router()
const readline = require('readline')

router.post('/api/tree-overview', async (req, res) => {
  try {
    var myInterface = readline.createInterface({
      input: fs.createReadStream('./ParsedTree.txt')
    })
    var array =  []
    myInterface.on('line', function(line) {
      array.push(line)
      console.log(line)
    })
    await res.send(array)
  } catch (e) {
    res.status(500).send(e)
  }
})

module.exports = router

res.send(array) is sending empty array how to make it wait for myInterface to finish running and send the data which is pushed.

solomyhansolo
  • 107
  • 2
  • 9
  • 1
    There are several problems above, but the main conceptual problem is explained by the [linked question](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron)'s answers: Your `line` callbacks won't have run yet at the time you're doing `res.send(array)`; they're called **later**. (Other problems: 1. You never assign anything to `array` [you've fixed that now], so the first `array.push(line)` will throw an error because `array` is `undefined`. 2. `res.send` doesn't return a promise, so there's no reason to `await` it.) – T.J. Crowder Feb 12 '20 at 15:04
  • 1
    To deal with the main problem, build up the array in response to `line` events as you are now, then do `res.send` in response to the [`close` event](https://nodejs.org/api/readline.html#readline_event_close) on the interface. Alternatively, use the fact that `Interface` is an async iterable by using `for-await-of` as shown [in one of the examples in the documentation](https://nodejs.org/api/readline.html#readline_example_read_file_stream_line_by_line)., then do `res.send` after the loop. – T.J. Crowder Feb 12 '20 at 15:06
  • 1
    close event worked, thanks a lot. – solomyhansolo Feb 13 '20 at 09:30

0 Answers0