trilium/src/routes/api/export.js

57 lines
1.8 KiB
JavaScript
Raw Normal View History

2017-12-03 10:48:22 +08:00
"use strict";
const express = require('express');
const router = express.Router();
const rimraf = require('rimraf');
const fs = require('fs');
const sql = require('../../services/sql');
const data_dir = require('../../services/data_dir');
const html = require('html');
2017-12-23 22:57:20 +08:00
const auth = require('../../services/auth');
const wrap = require('express-promise-wrap').wrap;
2017-12-03 10:48:22 +08:00
router.get('/:noteId/to/:directory', auth.checkApiAuth, wrap(async (req, res, next) => {
2017-12-03 10:48:22 +08:00
const noteId = req.params.noteId;
const directory = req.params.directory.replace(/[^0-9a-zA-Z_-]/gi, '');
if (!fs.existsSync(data_dir.EXPORT_DIR)) {
fs.mkdirSync(data_dir.EXPORT_DIR);
}
const completeExportDir = data_dir.EXPORT_DIR + '/' + directory;
if (fs.existsSync(completeExportDir)) {
rimraf.sync(completeExportDir);
}
fs.mkdirSync(completeExportDir);
const noteTreeId = await sql.getFirstValue('SELECT noteTreeId FROM note_tree WHERE noteId = ?', [noteId]);
await exportNote(noteTreeId, completeExportDir);
2017-12-03 10:48:22 +08:00
res.send({});
}));
2017-12-03 10:48:22 +08:00
async function exportNote(noteTreeId, dir) {
const noteTree = await sql.getFirst("SELECT * FROM note_tree WHERE noteTreeId = ?", [noteTreeId]);
2018-01-29 08:30:14 +08:00
const note = await sql.getFirst("SELECT * FROM notes WHERE noteId = ?", [noteTree.noteId]);
2018-01-29 08:30:14 +08:00
const pos = (noteTree.notePosition + '').padStart(4, '0');
2017-12-03 10:48:22 +08:00
2018-01-29 08:30:14 +08:00
fs.writeFileSync(dir + '/' + pos + '-' + note.title + '.html', html.prettyPrint(note.content, {indent_size: 2}));
2017-12-03 10:48:22 +08:00
const children = await sql.getAll("SELECT * FROM note_tree WHERE parentNoteId = ? AND isDeleted = 0", [note.noteId]);
2017-12-03 10:48:22 +08:00
if (children.length > 0) {
2018-01-29 08:30:14 +08:00
const childrenDir = dir + '/' + pos + '-' + note.title;
2017-12-03 10:48:22 +08:00
fs.mkdirSync(childrenDir);
for (const child of children) {
2018-01-29 08:30:14 +08:00
await exportNote(child.noteTreeId, childrenDir);
2017-12-03 10:48:22 +08:00
}
}
}
module.exports = router;