obsidian插件开发-常用文件操作
将要操作的文件目录结构如图所示
1 一、文件操作
1.1 创建文件
/**
* @public
*/
create(path: string, data: string, options?: DataWriteOptions): Promise<TFile>;
示例:在仓库根目录创建1.md
,内容为hello
this.app.vault.create("1.md", "hello");
示例:在仓库根的demo目录创建ok.md
,内容为world
注意:目录不存在会报错
this.app.vault.create("demo/ok.md", "hello");
1.2 重命名文件
调用fileManager
可以让obsidian自动更新里面的链接!
export class FileManager {
/**
* Rename or move a file safely, and update all links to it depending on the user's preferences.
* @param file - the file to rename
* @param newPath - the new path for the file
* @public
*/
renameFile(file: TAbstractFile, newPath: string): Promise<void>;
}
示例:修改 仓库根目录下的1.md
为2.md
const f = this.app.vault.getAbstractFileByPath("1.md")
this.app.fileManager.renameFile(f, "2.md")
如果仅仅修改文件名称可以调用this.app.vault.rename()
方法
1.3 获取所有文件
/**
* @public
*/
getFiles(): TFile[];
示例:获取所有文件
1.4 获取指定目录的文件列表
/**
* @public
*/
getAbstractFileByPath(path: string): TAbstractFile | null;
示例:获取posts下的所有文件
TAbstractFile
虽然没有children
这个属性,但是却能够调用,很奇怪?
this.app.vault.getAbstractFileByPath("content/posts").children
这段代码在obsidian的控制台上可以直接运行,然而当我们调用
npm run build
的时候却报错了.
经过查阅源码得知,TAbstractFile
确实没有children
属性,但是在运行过程中,控制台自动转换成了 TFolder
对象,所以没有报错。
然而编译的时候却难以确定到底是TFolder
还是TFile
,因此我们需要手动强转成TFolder
强转的语法是在变量前面加上尖括号指定类型名称: ``<类型>obj`
TAbstractFile
是一个抽象类
export abstract class TAbstractFile {
vault: Vault;
path: string;
name: string;
parent: TFolder;
}
TFile
也继承于`TAbstractFile
export class TFile extends TAbstractFile {
stat: FileStats;
basename: string;
extension: string;
}
TFolder
也继承于`TAbstractFile
export class TFolder extends TAbstractFile {
children: TAbstractFile[];
isRoot(): boolean;
}
TFile
和TFolder
都继承于TAbstractFile
,因此他们都可以调用TAbstractFile
的方法,同时拥有自己独特的方法,而children
是TFolder
独特的方法,因此我们需要将TAbstractFile
转换成TFolder
示例:获取指定目录下的所有目录,封装成Series对象数组并返回
interface Series {
title: string;
description: string;
}
/**
** @returns 获取系列,即content/series/下一级的所有目录名称。
*/
getSeries() :Series[] {
const p = this.app.vault?.getAbstractFileByPath("content/series")
console.log(p);
// <TFolder>变量名,强制转换
const series = (<TFolder>this.app.vault?.getAbstractFileByPath(
"content/series"))?.children
const arr = new Array<Series>();
series.forEach((item : any) => {
arr.push({title: item.name, description: item.name})
});
console.log(arr)
return arr;
}
2 二、文件夹操作
2.1 获取当前仓库系统目录
this.app.vault.adapter.basePath
2.2 创建文件夹
/**
* @public
*/
createFolder(path: string): Promise<void>;
示例:在仓库根目录下创建名称为hello的文件夹
this.app.vault.createFolder("hello");
结果:
|仓库
|hello
示例:创建多层目录
this.app.vault.createFolder("a/b/c");
结果:
|仓库
|a
|b
|c
3 结束语
在开发过程中遇到各种问题,可以去官网
obsidian-api 查看源码obsidian-api/obsidian.d.ts
获取帮助
参考: Vault - Developer Documentation (obsidian.md) obsidian-api/obsidian.d.ts at bde556afa033e909ebfb9fcee8f5ef288276f78f · obsidianmd/obsidian-api (github.com)