You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
potato-launcher/src/js/database/fileHandler.js

127 lines
2.8 KiB

import { v4 as uuidv4 } from 'uuid'
import md5 from 'md5'
import mkdirp from 'mkdirp'
import path from 'path'
import fs from 'fs'
/**
* handling files and create files in a hash-directory system
*
* @author Björn Hase
* @license https://www.gnu.org/licenses/gpl-3.0.en.html GPL-3
* @link https://gitea.node001.net/HerrHase/potato-launcher.git
*
*/
class FileHandler {
/**
*
*
* @param {string} storagePath
*
*/
constructor(storagePath) {
this.storagePath = storagePath
}
/**
* add file to storage
*
* @param {string} filename
* @param {string} type
* @param {mixed} data
* @return {object}
*
*/
put(filename, type, data) {
const uuid = uuidv4()
const relativePath = this._createDirPath(uuid) + '/' + uuid
try {
fs.writeFileSync(this.storagePath + '/' + relativePath, data, { encoding: 'binary' })
} catch(error) {
throw new Error(error)
}
return {
name: filename,
type: type,
path: relativePath
}
}
/**
* remove
*
* @param {object} file
*
*/
remove(file) {
fs.unlinkSync(this.storagePath + '/' + file.path)
}
/**
* read file from Blob as binary string
*
* @param {Object} file
* @return {mixed}
*
*/
readFileFromBlob(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = (response) => {
resolve(response.target.result)
}
reader.onerror = (error) => reject(error)
reader.readAsBinaryString(file)
})
}
/**
* creating directory for file,
* using filename and uniqid to get a hash and split
* him into chunks and creating directories
*
* @param {string} filename
* @return {string}
*/
_createDirPath(uuid) {
// getting hash
const hashPath = md5(uuid)
// creating string of relative path, and create missing directories
const relativePath = this._chunks(hashPath).join('/')
const absolutePath = this.storagePath + '/' + relativePath
mkdirp.sync(absolutePath)
return relativePath
}
/**
* split string into chunks
*
* @param {string} value
* @param {integer} size
* @return {array}
*/
_chunks(value, size = 8) {
let result = [];
if (value !== null) {
value = String(value);
size = ~~size;
result = size > 0 ? value.match(new RegExp('.{1,' + size + '}', 'g')) : [value];
}
return result;
}
}
export default FileHandler