2017-09-25 59 views
1

我試圖使用fs.readFile像這樣打字稿...fs.readFile(字符串,編碼) - TS2345

import {readFile} from 'fs'; 
let str = await readFile('my.file', 'utf8'); 

它導致這個錯誤:

TS2345: Argument of type '"utf8"' is not assignable to parameter of type '(err: ErrnoException, data: Buffer) => void'

我使用打字稿2.5.2,和@類型/節點8.0.30

+1

我不知道你的typeScript錯誤,但是你不能執行'await readFile(...)',因爲'readFile()'不返回一個承諾。 「await」只適用於返回承諾的函數。 – jfriend00

+0

@ jfriend00非常感謝您的支持,並沒有得到那麼多。我確實想知道,但無法找到異步等待的文檔。 – Drahcir

+0

網上有數百篇關於在Javascript中使用異步和等待的文章。你需要閱讀以瞭解他們的工作方式。你可以從這裏開始:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await – jfriend00

回答

0

的第三參數只能是一個字符串(編碼)時,第三是一個回調,請參閱類型定義簽名:

export function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; 

因此,通過增加一個回調,將工作:

readFile('my.file', 'utf8',() => { 

}); 

或者使用promisification庫來產生回調,並與await使用:

let str = promisify('my.file', 'utf8'); 
0

「await」是對Promises而不是回調。節點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) => { 
... 
}) 

快樂編碼!