Skip to content

Instantly share code, notes, and snippets.

@zaaack
Last active March 4, 2025 08:00
Show Gist options
  • Save zaaack/60439dadc38754fade64c8314aa980b6 to your computer and use it in GitHub Desktop.
Save zaaack/60439dadc38754fade64c8314aa980b6 to your computer and use it in GitHub Desktop.
joplin backup script like backup plugin with max backup count andonly backup when changes
const { execSync } = require('child_process');
const fs = require('fs');
const backupDir = __dirname + '/joplin-backups'
const backupCount = 20
fs.mkdirSync(backupDir, { recursive: true })
const joplinSyncDir = 'C:/Users/admin/我的坚果云/webdav/Joplin'
let lastUpdatedAt = 0
const lastUpdatedAtFile = backupDir + '/lastUpdatedAt.txt'
if (fs.existsSync(lastUpdatedAtFile)) {
lastUpdatedAt = parseFloat(fs.readFileSync(lastUpdatedAtFile, 'utf8'))
}
const files = fs.readdirSync(joplinSyncDir)
let curUpdatedAt = 0
for (const f of files) {
const stat = fs.statSync(joplinSyncDir + '/' + f)
if (stat.mtimeMs > curUpdatedAt) {
curUpdatedAt = stat.mtimeMs
}
}
fs.writeFileSync(lastUpdatedAtFile, curUpdatedAt.toString())
if (curUpdatedAt <= lastUpdatedAt) {
console.log('no update')
process.exit(0)
} else {
const dir = backupDir
console.log(execSync(`joplin sync`).toString())
console.log(execSync(`joplin export --format=jex ${dir}/${new Date().toLocaleString().replace(/\W+/g, '-') + '.jex'}`).toString())
const backupFiles = fs.readdirSync(dir)
const backups = []
for (const f of backupFiles) {
if (!f.endsWith('.jex')) continue
const stat = fs.statSync(dir + '/' + f)
backups.push({
file: f,
mtime: stat.mtimeMs,
})
}
backups.sort((a, b) => b.mtime - a.mtime)
for (let i = backupCount; i < backups.length; i++) {
fs.unlinkSync(dir + '/' + backups[i].file)
console.log('delete backup', backups[i].file)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment