Deno读取

读取目录


for await (const dirEntry of Deno.readDir(".")){
  console.log(dirEntry)
}
for (const dirEntry of Deno.readDirSync(".")){
  console.log(dirEntry)
}

读取文件

const data = Deno.readFileSync("hello.txt")
const decoder = new TextDecoder("utf-8")
console.log(decoder.decode(data))
const data = await Deno.readFile("hello.txt")
const decoder = new TextDecoder("utf-8")
console.log(decoder.decode(data))
const data = await Deno.readTextFile("hello.txt")
console.log(data)

小应用

读取在当前目录下后缀为.txt的文件

for (const dirEntry of Deno.readDirSync(".")){
  if(dirEntry.isFile){
    const index = dirEntry.name.lastIndexOf(".")
    const ext = dirEntry.name.substr(index)

    if(ext=='.txt'){
      console.log(dirEntry)
      const data =  Deno.readTextFileSync("hello.txt")
      console.log(data)
    }
   
  }
}

输入流

每次读取部分字节到buf

const file = await Deno.open("hello.txt", {read:true});
const buf = new Uint8Array(2000);  // 若数组长度不够,会出现乱码
const decoder = new TextDecoder("UTF-8");
let numberOfBytesRead : number|null;

while((numberOfBytesRead = await Deno.read(file.rid, buf))!=null){
  console.log(decoder.decode(buf))
}
Deno.close(file.rid);

读取所有字节到buf

const file = await Deno.open("hello.txt",{read: true});
const buf = new Uint8Array(100);
const decoder = new TextDecoder("UTF-8");
const fileContent = Deno.readAllSync(file);
console.log(decoder.decode(fileContent));
Deno.close(file.rid);

typescript小笔记

let a = Array 是一种泛型
Uint8Array.from(arr:any[]) 数组类型
Uint8Array.of(...arg:any[]) 可变参数类型

posted @ 2020-08-28 00:57  yyzhai  阅读(262)  评论(0)    收藏  举报