-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileStorage.ts
More file actions
59 lines (50 loc) · 1.72 KB
/
fileStorage.ts
File metadata and controls
59 lines (50 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* Reference taken from npm docs
* https://www.npmjs.com/package/multer
*/
/**
* For production and highly scalable environments, the best approach would be to use AWS S3/Google Cloud storage/Azure BLOB storage
* However, those are easy to integrate and since this is a test project, I didn't wanna shell any money :P
* So, we will have our very own file storage system. Win-Win!
*/
/**
* IMPORTANT: Have all the file storage utility functions defined in this file only to keep the relative path of the files same.
*/
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import config from './config';
// Check if the upload directory exists
// If not, create one
// NOTE: A new directory uploads/ will be created where all the uploaded files will be written
const fileStoragePath = config.FILES_STORAGE_LOCATION;
if (!fs.existsSync(fileStoragePath)) {
// If not, create the directory
fs.mkdirSync(fileStoragePath);
}
export const storage = multer.diskStorage({
destination: function (req, file, cb) {
// Function to get the destination folder
cb(null, `${fileStoragePath}/`);
},
filename: function (req, file, cb) {
// This function will be called to get the filename for the file. Return unique file names from here.
cb(null, 'file-' + Date.now() + path.extname(file.originalname));
}
});
export const deleteFile = (filePath: string) => {
try {
fs.unlinkSync(filePath);
}
catch (err) { }
}
export const getFileData = (filePath: string) => {
let data: any = '';
try {
data = fs.readFileSync(filePath).toString('base64');
}
catch (err) {
console.log("Error while reading file", err);
}
return data;
}