0

I'm actually fighting with Promises on js. I have a function where I want to return a value.
How do I call the return value?
I searched various sources, but didn't get the hang of it.

Thankyou very much in advance!!!

class ReadFile{
    constructor(){
        this.fs = require('fs')
    }

    async readData(pathToFile){
        const readStream = this.fs.createReadStream(pathToFile, 'utf-8'); 
        readStream.on('data', (chunk) => {
            return chunk;
        })
    }
}

const read = new ReadFile();
read.readData('./resources/src/index.html').then(console.log);
Steve
  • 4,372
  • 26
  • 37
buxxxbaum
  • 65
  • 6
  • 2
    `readData()` doesn't return anything (explicitly) – Andreas Nov 11 '21 at 11:42
  • `Promise.resolve()` the complete data when the `end` event happens. See https://nodejs.org/dist/latest-v16.x/docs/api/stream.html#event-end – Lin Du Nov 11 '21 at 11:44
  • Why are you trying to wrap it in a `Promise()`? This doesn't make much sense, at least not with the `data` event, because that one can be triggered multiple times: _"The 'data' event is emitted whenever the stream is relinquishing ownership of a chunk of data to a consumer. This may occur whenever the stream is switched in flowing mode by calling readable.pipe(), readable.resume(), or by attaching a listener callback to the 'data' event. The 'data' event will also be emitted whenever the readable.read() method is called and a chunk of data is available to be returned."_ – Andreas Nov 11 '21 at 11:49

0 Answers0