Promisify FileReader in Node 8+

#1

I’ve spent almost no time paying attention to NodeJS, been focused on changes to Ionic. But Node introduced something pretty cool in version 8. So it’s old news, but my guess is that it will still be new news to some people here.

There’s now a promisify function in Node. So instead of putting FileReader inside new Promise, to get away from callback hell, you can use Node’s fs library like this:

import { promisify } from 'util';
import { readFile } from 'fs';

readFilePromise(filename: string): Promise<Buffer> {
    return promisify(readFile)(filename);
  }

Buffer is a Node interface that is basically an arraylike of raw data, that can be translated to string, JSON, etc.

1 Like
#2

Ironically, Angular 6 has just removed support for the NodeJS fs library. This was intentional, see here. So the code I posted won’t work in Ionic 4, but is still supported in Ionic 3/Angular 4.