引入依赖

1
import { Plugin, fs } from "@typora-community-plugin/core";

是否可以访问

1
2
3
4
5
6
try {
await fs.access(path);
console.log(`${path} 可访问。`);
} catch (error) {
console.error(`${path} 不可访问:${error}`);
}

文件是否存在

1
2
3
4
5
6
const exists = await fs.exists(path);
if (exists) {
console.log(`${path} 存在。`);
} else {
console.log(`${path} 不存在。`);
}

文件类型

1
2
3
4
5
6
7
8
const stats = await fs.stat(path);
if (stats.isDirectory()) {
console.log(`${path} 是一个目录。`);
} else if (stats.isFile()) {
console.log(`${path} 是一个文件。`);
} else {
console.log(`${path} 是其他类型。`);
}

创建目录

1
2
3
4
5
6
try {
await fs.mkdir(path + "/mkdir");
console.log(`目录 ${path + "/mkdir"} 创建成功。`);
} catch (error) {
console.error(`创建目录 ${path + "/mkdir"} 时出错:${error}`);
}

复制文件

1
2
3
4
5
6
try {
await fs.copy(path + "/mkdir", path + "/mkdir_copy");
console.log(`文件从 ${path + "/mkdir"} 复制到 ${path + "/mkdir_copy"} 成功。`);
} catch (error) {
console.error(`复制文件时出错:${error}`);
}

移动文件

1
2
3
4
5
6
try {
await fs.move(path + "/mkdir", path + "/mkdir_move");
console.log(`文件从 ${path + "/mkdir"} 移动到 ${path + "/mkdir_move"} 成功。`);
} catch (error) {
console.error(`移动文件时出错:${error}`);
}

文件列表

1
2
3
4
5
6
7
try {
const items = await fs.list(path);
console.log(`目录 ${path} 的内容:`);
items.forEach((item) => console.log(item));
} catch (error) {
console.error(`列出目录 ${path} 内容时出错:${error}`);
}

同步覆盖文件内容

1
2
3
4
5
6
try {
await fs.writeText(path, "Hello, world!");
console.log(`文件 ${path} 的内容:`);
} catch (error) {
console.error(`写入文件 ${path} 时出错:${error}`);
}

同步追加文件内容

1
2
3
4
5
6
7
try {
await fs.appendText(path, "Hello, world! 1");
await fs.appendText(path, "Hello, world! 2");
console.log(`文件 ${path} 的内容:`);
} catch (error) {
console.error(`写入文件 ${path} 时出错:${error}`);
}

同步读取文件内容

1
2
3
4
5
6
try {
const content = fs.readTextSync(path);
console.log(`文件 ${path} 的同步内容:\n${content}`);
} catch (error) {
console.error(`同步读取文件 ${path} 时出错:${error}`);
}

异步读取文件内容

1
2
3
4
5
6
try {
const content = await fs.readText(path);
console.log(`文件 ${path} 的内容:\n${content}`);
} catch (error) {
console.error(`读取文件 ${path} 时出错:${error}`);
}