mirror of
https://github.com/BoostIo/Boostnote
synced 2025-12-13 09:46:22 +00:00
Export note with local images
Looks through the note and searches for local images. Copies them to ‘images’ folder in the export path and replaces affected links. #1261
This commit is contained in:
67
browser/main/lib/dataApi/exportNote.js
Executable file
67
browser/main/lib/dataApi/exportNote.js
Executable file
@@ -0,0 +1,67 @@
|
||||
import exportImage from 'browser/main/lib/dataApi/exportImage'
|
||||
import {findStorage} from 'browser/lib/findStorage'
|
||||
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
|
||||
/**
|
||||
* Export note together with images
|
||||
*
|
||||
* If images is stored in the storage, creates 'images' subfolder in target directory
|
||||
* and copies images to it. Changes links to images in the content of the note
|
||||
*
|
||||
* @param {String} storageKey
|
||||
* @param {String} noteContent Content to export
|
||||
* @param {String} targetPath Path to exported file
|
||||
* @return {Promise.<*[]>}
|
||||
*/
|
||||
function exportNote (storageKey, noteContent, targetPath) {
|
||||
const targetStorage = findStorage(storageKey)
|
||||
const storagedImagesRe = /!\[(.*?)\]\(\s*?\/:storage\/(.*\.\S*?)\)/gi
|
||||
const exportTasks = []
|
||||
const images = []
|
||||
|
||||
const exportedData = noteContent.replace(storagedImagesRe, (match, dstFilename, srcFilename) => {
|
||||
if (!path.extname(dstFilename)) {
|
||||
dstFilename += path.extname(srcFilename)
|
||||
}
|
||||
const imagePath = path.join('images', dstFilename)
|
||||
|
||||
exportTasks.push(
|
||||
exportImage(targetStorage.path, srcFilename, path.dirname(targetPath), dstFilename)
|
||||
)
|
||||
images.push(imagePath)
|
||||
return ``
|
||||
})
|
||||
|
||||
exportTasks.push(exportFile(exportedData, targetPath))
|
||||
return Promise.all(exportTasks)
|
||||
.catch((err) => {
|
||||
rollbackExport(images)
|
||||
throw err
|
||||
})
|
||||
}
|
||||
|
||||
function exportFile (data, filename) {
|
||||
return new Promise((resolve, reject) => {
|
||||
fs.writeFile(filename, data, (err) => {
|
||||
if (err) throw err
|
||||
|
||||
resolve(filename)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove exported images
|
||||
* @param imagesPaths
|
||||
*/
|
||||
function rollbackExport (imagesPaths) {
|
||||
imagesPaths.forEach((path) => {
|
||||
if (fs.existsSync(path)) {
|
||||
fs.unlink(path)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export default exportNote
|
||||
Reference in New Issue
Block a user