-
-
Save sergeysova/af96f673465726b359b45a4ace42cf95 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
const path = require('path') | |
const fileType = require('file-type') | |
const base64 = require('base64-arraybuffer') | |
const crypto = require('crypto') | |
const makeDir = require('make-dir') | |
const fs = require('co-fs') | |
const defaultOptions = { | |
pathStorage: '.', | |
algorithm: 'md5', | |
exclude: '', | |
extension: ['png', 'jpg', 'jpeg'], | |
} | |
const makeHash = (content, algo) => crypto | |
.createHash(algo) | |
.update(content) | |
.digest('hext') | |
const writeFile = (filePath, binary) => fs.writeFile(filePath, binary, 'base64') | |
async function saveFile(original, inputOptions = defaultOptions) { | |
const options = Object.assign({}, defaultOptions, inputOptions) | |
const content = original.replace(/^data:.+;base64,/, '') | |
const arrayBuff = base64.decode(content) | |
const type = fileType(arrayBuff) | |
if (type == null || options.extension.indexOf(type.ext) === -1) { | |
throw new Error('File type is not supported') | |
} | |
const hash = makeHash(content) | |
const rootDir = hash.substring(0, 2) | |
const subDir = hash.substring(2, 4) | |
const dir = path.join(options.pathStorage, rootDir, subDir) | |
const filePath = path.join(dir, `${hash}.${type.ext}`) | |
try { | |
await makeDir(dir) | |
await writeFile(filePath, content) | |
} | |
catch (error) { | |
throw new Error('Cannot save file', error) | |
} | |
if (options.exclude) { | |
return filePath.replace(options.exclude, '') | |
} | |
return filePath | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment