Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
News-Website-Second-Year-Project-Copy/modules/imagefs.js
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
49 lines (42 sloc)
1.33 KB
This file contains 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' | |
const fs = require('fs') | |
const util = require('util') | |
const mime = require('mime-types') | |
const copy = util.promisify(fs.copyFile) | |
const unlink = util.promisify(fs.unlink) | |
const exists = util.promisify(fs.exists) | |
const uploadPicture = async(path, mimeType, fileName, newPath) => { | |
try{ | |
if(path.length === 0) throw new Error('path is blank') | |
if(mimeType.length === 0) throw new Error('mimeType is blank') | |
const extension = mime.extension(mimeType) | |
const acceptedExtension = ['jpg', 'png', 'webp', 'tiff', 'gif', 'svg'] | |
if(acceptedExtension.includes(extension) === false) throw new Error('file type is not suitable for upload') | |
const newFile = `${newPath}${fileName}.${extension}` | |
await copy(path, newFile) | |
return true | |
} catch(err) { | |
throw err | |
} | |
} | |
const deletePicture = async(targetFile) => { | |
try{ | |
if(await exists(`${targetFile}`) === false) throw new Error('image file does not exist') | |
await unlink(`${targetFile}`) | |
return true | |
} catch(err) { | |
throw err | |
} | |
} | |
const renamePicture = async(targetFile, newName) => { | |
try{ | |
if(await exists(`${targetFile}`) === false) throw new Error('file does not exist') | |
const name = String(newName) | |
await copy(`${targetFile}`, `${name}`) | |
await unlink(`${targetFile}`) | |
return true | |
} catch(err) { | |
throw err | |
} | |
} | |
module.exports = {uploadPicture, deletePicture, renamePicture} |