Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fs.readFile(string, encoding) - TS2345

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

like image 444
Drahcir Avatar asked Sep 18 '25 03:09

Drahcir


2 Answers

"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!

like image 55
Parav01d Avatar answered Sep 20 '25 16:09

Parav01d


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');
like image 37
Drahcir Avatar answered Sep 20 '25 16:09

Drahcir