2021年5月5日水曜日

denoでテキストファイルを読み込む

Deno.readAllで得られる値の型はUint8Arrayなので、文字列として扱うためにはTextDecoderを併用する必要がある。
読み込んでconsoleに表示するだけのサンプルが以下。
async function テキストファイルを読み込む(path:string): Promise<string> {
const file = await Deno.open(path, {read: true})
const data = await await Deno.readAll(file)
Deno.close(file.rid)
const text = new TextDecoder().decode(data)
return text
}
const text = await テキストファイルを読み込む('C:\\deno\\1.10.1\\test.txt')
console.log(text)




この投稿を作成しながらdeno docを見ていたら「Deno.readTextFile」というメソッドがある事に気が付いた…。

const text = await Deno.readTextFile('C:\\deno\\1.10.1\\test.txt')
console.log(text)

実行結果

0 件のコメント:

コメントを投稿