Deno文件处理详解:如何写入文件、如何读文件、如何创建删除以及检查文件和目录。

原文地址:Deno文件处理详解:如何写入文件、如何读文件、如何创建删除以及检查文...

Deno带有自己的文件系统作为核心模块。该文件系统模块可用于任何类型的文件或目录操作。在本教程分享了在Deno应用程序中文件处理的方法示例:如何写入文件、如何读文件、如何创建删除以及检查文件和目录。

目前,一些方法仍处于试验阶段,并且非常不稳定。使用这些方法时,应始终添加标志。--unstable

我们将向您介绍以下内容:

  • 如何在Deno中写入文件
  • 如何在Deno中读取文件
  • 删除Deno(removeremoveSync)中的文件
  • 检查目录中的文件夹(ensureDir)
  • 复制文件内容(copy)
  • 检查目录(exists)
  • 检查文件是否存在(ensureFile)
  • 如何在Deno(emptyDir)中清空目录
  • 在Deno中创建CLI应用程序

如何在Deno中写入文件

有几种方法可以在Deno中写入文件。它们都需要标志,并且如果发生则将引发错误。--allow-write

您可以使用或将文本写入文件。具有同步和异步格式,并带有两个参数:文件的位置和下面要写入文件的内容。Deno.writeTextFileDeno.writeFileDeno.writeTextFile

// using the async method
await Deno.writeTextFile('./file.txt', 'This is the content to be written');

//using sync method
Deno.writeTextFileSync('./file.txt', 'This is the content to be written');

你也可以使用带有TextEncoder的Deno.writeFile方法,TextEncoder方法可以转换字符串为Unit8Array:

const encoder = new TextEncoder(); // to convert a string to Uint8Array
await Deno.writeFile("./file.txt", encoder.encode("Content to be written"));

最后,你可以说好用Deno.open和Deno.writeAll方法打开一个文件,写入内容,然后关闭文件。

const file = await Deno.open("./image.png", { write: true, create: true }); //this opens the file
await Deno.writeAll(file, imageBytes); //writes to file
file.close(); // closes the file

如果你想写入内容到一个不存在文件,Deno会自动创建这个文件。

Deno如何读文件

像写文件一样,Deno有多种读文件方法,并且这些每一个方法都需要--allow-read参数。

你可以使用Deno.readTextFile和Deno.readFile方法去读一个文件。Deno.readTextFile提供同步和异步方法,并且将路径做为参数:

// using the async method
const text = await Deno.readTextFile("file.txt");
console.log(text);

//using the sync method
const sync = Deno.readTextFileSync("file.txt");
console.log(sync);

另一个方法是Deno.readFile。你必须首先使用TextDecoder方法将文件解码到一个可读的格式。

const decoder = new TextDecoder("utf-8");
const text = decoder.decode(await Deno.readFile("file.txt"));

console.log(text);

在Deno中移除或者说删除文件(remove and removeSync)

想要在Deno删除文件,使用remove和removeSync方法。

// Deno remove file asynchronous (non-block)
await Deno.remove("file.txt");

// Deno remove file synchronous (blocking way)
Deno.removeSync("image.png");

如果尝试删除不存在的文件,则Deno会引发错误。

Uncaught NotFound: No such file or directory (os error 2)

检查目录中的文件夹(ensureDir)

ensureDir方法可确保您的工作目录中存在一个文件夹。您可以使用它来编写一个简单的程序。

让我们编写一个简单的程序来检查文件夹是否存在。如果该文件夹存在,它将创建一个新文件并向其中添加一些文本内容。

要使用此方法,必须将其导入到应用程序中。notes在工作目录中创建一个文件夹。这是您存储笔记的地方。

import { ensureDir, ensureDirSync } from "https://deno.land/std/fs/mod.ts";

与到目前为止我们讨论过的其他方法一样,该方法有异步和同步格式。这是使用异步方法的方法:

ensureDir("./notes")
 .then(() => Deno.writeTextFile("./notes/note1.txt", "This is the content for note 1")); 

复制文件内容(copy)

copy方法使您可以将文件内容复制到另一个文件。

要将copy方法导入到Deno应用程序中:

import { copy } from "https://deno.land/std/fs/mod.ts";
copy("file.txt", "test.txt", {
 overwrite: true,
});

此方法将文件内容从复制到。它还需要一些选择。例如,该选项将覆盖您要将内容复制到的文件的内容。file.txttest.txtoverwrite

检查目录(exists)

exists方法检查目录是否存在。exists返回一个Promise而existsSync返回一个布尔值。

让我们编写一个简单的程序,该程序将检查目录是否存在:

import { exists, existsSync } from "https://deno.land/std/fs/mod.ts";

exists("./notes").then((res) => console.log(res)); //res here returns a boolean
 //or do this
let fileExists = existsSync("./notes"); 
console.log(fileExists);// returns boolean

检查文件是否存在(ensureFile)

ensureFile 确保文件存在。

让我们编写一个简单的程序进行试验:

import { ensureFile, ensureFileSync } from "https://deno.land/std/fs/mod.ts";
let ok = ensureFileSync("./read.ts");

如果该文件不存在,Deno会自动创建它。同样,请记住添加——不稳定标志,因为其中一些方法仍处于试验阶段。

如何在Deno(emptyDir)中清空目录

emptyDir方法检查目录是否为空。如果指定的目录包含任何文件或目录,则Deno清空该目录。

import { emptyDir } from "https://deno.land/std/fs/mod.ts";

emptyDir("./notes").then((res) => console.log("res", res)); // this method return a promise.

使用Deno创建一个CLI应用

现在让我们创建一个简单的CLI应用程序,它将为我们创建文件。我们将使用终端来创建这个文件。

Deno.args返回在命令中传递的所有参数。这样,我们就可以创建一个简单的应用程序。我们的命令将保存我们想要创建的文件的名称。

运行以下:

deno run main.ts create-file test.ts.

这个命令有两个参数:create-file和test.ts。如果我们记录Deno.args,它将返回一个数组中的参数。

我们可以使用它来检查用户是否传递了创建文件参数并为文件提供了一个名称:

let params = Deno.args;
console.log(params);
let createFile = () => {
 if (params[0] !== "create-file") {
 console.log(
 `${params[0]} is not a valid command, Did you mean 'create-file'`,
 );
 return false;
 } else if (!params[1]) {
 console.log(
 `You need to provide a name of a file`,
 );
 return false;
 } else {
 Deno.writeTextFileSync(`./${params[1]}`, "//This is your created file");
 }
};
createFile();

现在运行应用程序,打开你的终端,运行以下程序:

deno run --allow-all main.ts create-file <name of file>

记住添加 --allow-all 或者 --allow-write 文件参数

总结

如Deno的文件系统非常通用,将文件写入Deno时需要考虑多种方法和方案。知道如何使用同步和异步方法总是有好处的,因为它们都有用例。写入较大的文件时,应考虑使用分片写入功能。

原文地址:https://www.cnblogs.com/livelab/p/14111142.html