deno之文件操作
时间:2021-07-08 04:05:51
文件操作
readFile
function Deno.readFile(path: string): Promise<Uint8Array>
--allow-read
异步读取文件,返回的数据类型是
Uint8Array
,需要通过TextDecoder
解码.
const decoder = new TextDecoder('utf-8');
const data = await Deno.readFile('hello.txt');
console.log(decoder.decode(data));
readFileSync
同步读取文件,用法同
readFile
const { readFile, readFileSync } = Deno;
/**
* @method getDecoder
* @description 获取解码器
* @param encoding 文件编码
*/
function getDecoder(encoding: string): TextDecoder {
return new TextDecoder(encoding);
}
/**
* @method read
* @description 异步读取文件
* @param path 文件路径
* @param encoding 文件编码
*/
export async function read(path: string, encoding: string = 'utf-8'): Promise<string> {
const decoder = getDecoder(encoding);
const data = await readFile(path);
return decoder.decode(data);
}
/**
* @method readSync
* @description 同步读取文件
* @param path 文件路径
* @param encoding 文件编码
*/
export function readSync(path: string, encoding: string = 'utf-8'): string {
const decoder = getDecoder(encoding);
const data = readFileSync(path);
return decoder.decode(data);
}
writeFile
function Deno.writeFile(path: string, data: Uint8Array, options?: WriteFileOptions): Promise<void>
--allow-write
异步写入文件,写入的数据类型是
Uint8Array
,需要通过TextEncoder
编码数据.
const encoder = new TextEncoder();
const data = encoder.encode('Hello world\n');
await Deno.writeFile('hello1.txt', data);
writeFileSync
同步写入文件,用法同
writeFile
writeTextFile
function Deno.writeTextFile(path: string, data: string): Promise<void>
--allow-write
异步写入文本文件,写入的数据类型是
string
writeTextFileSync
同步写入文本文件,用法同
writeTextFile
const { writeFile, writeFileSync, writeTextFile, writeTextFileSync } = Deno;
/**
* @method encode
* @description 编码数据
* @param data 要编码的数据
*/
function encode(data: string): Uint8Array {
const decoder = new TextEncoder();
return decoder.encode(data);
}
/**
* @method write
* @description 异步写文件
* @param path 文件路径
* @param data 写入数据
* @param options 写入参数
*/
export async function write(
path: string,
data: any,
options: Deno.WriteFileOptions = {}
): Promise<void> {
const enData = encode(data);
return await writeFile(path, enData, options);
}
/**
* @method write
* @description 异步写文件
* @param path 文件路径
* @param data 写入数据
* @param options 写入参数
*/
export function writeSync(path: string, data: any, options: Deno.WriteFileOptions = {}) {
const enData = encode(data);
writeFileSync(path, enData, options);
}
/**
* @method writeText
* @description 异步写入string数据
* @param path 文件路径
* @param text 写入数据
*/
export async function writeText(path: string, text: string) {
return await writeTextFile(path, text);
}
/**
* @method writeTextSync
* @description 同步写入string数据
* @param path 文件路径
* @param text 写入数据
*/
export function writeTextSync(path: string, text: string) {
return writeTextFileSync(path, text);
}