自动同步本地文档到博客
直接本地编辑自动同步博客
作者: lookroot
日期: 2025/08/02
前面的文章说过我从在线文档切换到了本地文档,使用Typora编辑,使用nas实现多端同步和备份文档。
感兴趣的可以看看
既然博客也是自己写的,也想偷偷懒,直接本地编辑自动同步博客,可图片上传插件一样还是使用node来写(没啥,单纯就是简单快捷),想控制脚本大小可以使用rust、go、 c都可以。
思路就是使用chokidar来监听本地文件变更,然后读取内容通过接口调用同步给博客。
import chokidar from 'chokidar';
import yaml from 'js-yaml';
import fs from 'fs';
import axios from 'axios';
/**
* ignoreInitial 是否忽略初始状态,默认true
* persistent 是否持续监听,默认true
* ignored 忽略的文件或文件夹,支持正则表达式
*/
const watcher = chokidar.watch('./notes', {
persistent: true,
ignoreInitial: true,
});
watcher
.on('add', path => addNote(path))
.on('change', path => changeNote(path))
.on('unlink', path => delNote(path))
.on('error', error => console.error(`监听错误: ${error}`));
function delNote(path: string) {
console.log(`文件删除: ${path}`);
}
function addNote(path: string) {
console.log(`文件添加: ${path}`);
}
function changeNote(path: string) {
console.log(`文件修改: ${path}`);
try {
readFile(path);
} catch (error) {
console.error(`读取文件错误: ${error}`);
}
}
interface Note {
header: Metadata;
content: string;
}
interface Metadata {
uuid: string;
title: string;
channel: string;
keywords: string[];
time: string;
show: boolean;
publish: boolean;
headImg: string
}
function readFile(path: string) {
const content = fs.readFileSync(path, 'utf8');
const metadata = yaml.load(content.split('```metadata')[1].split('```')[0]) as Metadata;
if (!metadata.publish) {
return
}
const contentWithoutHeader = content.split('```')[2];
const note: Note = {
header: metadata,
content: contentWithoutHeader,
};
//发送axios请求
axios.post('xxxxx', note)
.then(res => {
console.log(res.data);
}).catch(err => {
console.log(err);
})
console.log(note);
}
console.log('开始监听./notes目录...');
定义一个通用的header,用来作为博客的参数,直接传递接口就行。
使用展示:
```metadata
title: DDDD222
headImg: 1232
channel: 123123
keywords:
- tag12
- tag2
time: 17500032
publish: false
uuid: today2222
show: true
```
## 这是美好的一天
这是美好的一天
顺便推荐下开发测试和打包的命令,当然方式有很多。
"scripts": {
"start": "node dist/index.js",
"build": "tsc && pkg dist/index.js --output watch-markdown",
"watch": "nodemon your-script.js"
},