fs.readFile(string,编码) – TS2345
我试图使用fs.readFile
的打字稿fs.readFile
…
import {readFile} from 'fs'; let str = await readFile('my.file', 'utf8');
它导致这个错误:
TS2345:types'“utf8”'的参数不能分配给'(err:ErrnoException,data:Buffer)=> void'
我正在使用Typescript 2.5.2 ,和@ types / node 8.0.30
第三个参数只能是一个string(编码),当第三个是callback时,请参见types定义中的签名:
export function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException, data: string) => void): void;
所以通过添加callback它将工作:
readFile('my.file', 'utf8', () => { });
或使用promisification库生成callback和使用await
:
let str = promisify('my.file', 'utf8');
“等待”是对Promises而不是callback。 节点8.5.0支持从头开始promisify。 使用
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) => { ... })
快乐编码!