I'm trying to use fs.readFile
with typescript like this...
import {readFile} from 'fs';
let str = await readFile('my.file', 'utf8');
It results in this error:
TS2345: Argument of type '"utf8"' is not assignable to parameter of type '(err: ErrnoException, data: Buffer) => void'
I'm using Typescript 2.5.2, and @types/node 8.0.30
"await" is for Promises not for callbacks. Node 8.5.0 supports promisify from scratch. Use
const util = require('util');
const fs = require('fs');
const asyncReadFile = util.promisify(fs.read);
let str = await asyncReadFile('my.file', 'utf8');
//OR
asyncReadFile('my.file', 'utf8').then( (str) => {
...
})
Happy Coding!
The 3rd argument can only be a string (encoding) when the 3rd is a callback, see the signature in the type definitions:
export function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException, data: string) => void): void;
So by adding a callback it will work:
readFile('my.file', 'utf8', () => {
});
Or use a promisification library to generate the callback and use with await
:
let str = promisify('my.file', 'utf8');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With