0

So I'm trying to make fs module object oriented and i made this method it returns undefined but when i remove it and run it it works. whats wrong?

readFileAsync = () => {
        fs.readFile(this.filename, (err, data) => {
            if (err) {
                throw new err;
            } else {
                return data.toString();
            }
        })
}
  • `.readFile()` is already asynchronous (which is also the "problem" you have) – Andreas Aug 27 '21 at 12:32
  • @Andreas So changes i can make? remove that method? –  Aug 27 '21 at 12:33
  • 2
    @Haiderali - Or make it return a [promise](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises), but note that there's already a promise-based version of `readFile` in the standard Node.js API. – T.J. Crowder Aug 27 '21 at 12:34
  • @T.J.Crowder You mean make a new Promise and return it? –  Aug 27 '21 at 12:38
  • 1
    @Haiderali - See the link. But again, [that function already exists](https://nodejs.org/api/fs.html#fs_fspromises_readfile_path_options), I'd just use it. – T.J. Crowder Aug 27 '21 at 12:45
  • @T.J.Crowder You mean that what I’m doing is useless right? Cuz the function already exists –  Aug 27 '21 at 12:59
  • @Haiderali - I'm saying that writing a promise wrapper around `fs.readFile` would be pointless; there already is one. I don't know what the broader scope of what you're doing is, so can't comment on that. – T.J. Crowder Aug 27 '21 at 13:21

0 Answers0