Last active
June 23, 2017 21:23
-
-
Save NekrasovEV/c647e1bcbe52d06110fd515dc5a93f6c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
class FileManager { | |
constructor({pathStorage = '.', algorithm = 'md5', exclude = '', extension = ['png','jpg','jpeg']} = {}) { | |
this.pathStorage = pathStorage; | |
this.algorithm = algorithm; | |
this.exclude = exclude; | |
this.extension = extension; | |
} | |
hashGenerate(binary) { | |
let crypto = require('crypto'); | |
let hash = crypto.createHash(this.algorithm).update(binary).digest("hex"); | |
return hash; | |
} | |
mkDir(dir) { | |
let mkdirp = require('mkdirp'); | |
return new Promise((resolve, reject) => { | |
mkdirp(dir, (err) => { | |
if (err) | |
return reject(err); | |
else | |
return resolve(true); | |
}); | |
}) | |
} | |
async saveFile(path, binary) { | |
let fs = require('co-fs'); | |
let result = true; | |
try { | |
await fs.writeFile(path, binary, 'base64'); | |
} catch (err) { | |
result = false; | |
} | |
return result; | |
} | |
async run(binary) { | |
let hash; | |
const path = require('path'); | |
const fileType = require('file-type'); | |
const base64_arraybuffer = require('base64-arraybuffer'); | |
let result; | |
let rootDir; | |
let subDir; | |
let dir; | |
let filePath; | |
binary = binary.replace(/^data:.+;base64,/, ''); | |
let arrayBuff = base64_arraybuffer.decode(binary); | |
let type= fileType(arrayBuff); | |
if(type == null|| this.extension.indexOf(type.ext) == -1) | |
throw Error("Не поддерживаемый тип файла"); | |
hash = this.hashGenerate(binary); | |
rootDir = hash.substring(0, 2); | |
subDir = hash.substring(2, 4); | |
dir = path.join(this.pathStorage, rootDir, subDir); | |
filePath = path.join(dir, `${hash}.${type.ext}`); | |
if (await this.mkDir(dir)) { | |
await this.saveFile(filePath, binary); | |
result = filePath; | |
} | |
if (this.exclude) | |
result = result.replace(this.exclude, ''); | |
return result; | |
} | |
} | |
module.exports = FileManager; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment