Drahcir
Drahcir

Reputation: 11982

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

Upvotes: 4

Views: 12449

Answers (4)

Craig  Hicks
Craig Hicks

Reputation: 2588

I'm using Typescript 4.2 and 'fs/promises'. I had the same problem. This worked

import * as fsp from 'fs/promises'
await fsp.writeFile(filename, data,'utf-8' as BufferEncoding)

We can find in the file .../node_modules/@types/node/globals.d.ts the definition for BufferEncoding:

// Buffer class
type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex";

So "utf-8" (or some other valid string) is correct, but the typescript compiler needs a nudge to figure it out. Typescript is hard, even for the compiler.

Upvotes: 1

Macilias
Macilias

Reputation: 3543

Promisify didn't work in my case either. I managed similar task finally by ensuring that the file has been saved with 'utf8' encoding and the following way to read it:

let asset_content = null;
try {
    await RNFetchBlob.fs.readFile(assetFile_path, 'utf8')
      .then((data) => {
        asset_content = data;
        console.log("got data: ", data);
      })
      .catch((e) => {
        console.error("got error: ", e);
      })
  } catch (err) {
    console.log('ERROR:', err);
}
const assets = JSON.parse(asset_content);

Upvotes: 0

Parav01d
Parav01d

Reputation: 318

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

Upvotes: 3

Drahcir
Drahcir

Reputation: 11982

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');

Upvotes: 1

Related Questions