2
0
mirror of https://github.com/frappe/books.git synced 2024-12-25 12:10:06 +00:00
books/server/utils.js

91 lines
3.0 KiB
JavaScript
Raw Normal View History

2018-03-30 16:57:25 +00:00
const mkdirp = require('mkdirp');
const fs = require('fs');
const path = require('path');
const getDirName = path.dirname;
const os = require('os');
const sharp = require('sharp');
2018-03-30 16:57:25 +00:00
module.exports = {
writeFile(fullpath, contents) {
return new Promise((resolve, reject) => {
mkdirp(getDirName(fullpath), (err) => {
if (err) reject(err);
fs.writeFile(fullpath, contents, (err) => {
if (err) reject(err);
resolve();
});
});
});
},
2018-07-14 16:31:14 +00:00
readFile(filepath) {
return fs.readFileSync(filepath, 'utf-8');
2018-07-14 16:31:14 +00:00
},
getTmpDir() {
return os.tmpdir();
},
thumbnailMiddleware(staticPath) {
return function (req, res, next) {
const filename = req.path.split(path.sep).slice(-1)[0]
const dimension = req.query.size || null
const staticFile = path.join(staticPath, filename)
fs.exists(staticFile, (exists) => {
if (!exists) {
return next()
}
fs.stat(staticFile, (err, stats) => {
if (err) {
throw err
}
//Check if url is static file
if (stats.isFile()) {
// Check if url has dimension parameters
if (dimension) {
let [width, height] = dimension.split('x');
width = +width;
height = +height;
const thumbnailPath = path.join(staticPath, 'thumbnails');
const destination = path.join(thumbnailPath, `${width}x${height}-${filename}`)
// create thumbnails folder if not exists
if (!fs.existsSync(thumbnailPath)) {
fs.mkdirSync(thumbnailPath);
}
// Check if thumbnail already present
fs.existsSync(destination, (exists) => {
if (exists)
return res.sendFile(destination)
})
// Resize image
sharp(staticFile)
.resize(width, height)
.toFile(destination)
.then(() => {
return res.sendFile(destination)
})
.catch(err => {
console.error(err)
})
} else {
return res.sendFile(staticFile)
}
} else {
// File is not static
return next()
}
})
})
}
2018-03-30 16:57:25 +00:00
}
}