-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
87 lines (81 loc) · 2.42 KB
/
server.js
File metadata and controls
87 lines (81 loc) · 2.42 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"use strict";
const express = require("express");
const cors = require("cors");
const multer = require("multer");
const loki = require("lokijs");
const fs = require("fs");
const del = require("del");
const path = require("path");
const app = express();
app.use(cors());
app.use("/public", express.static(process.cwd() + "/public"));
app.get("/", function(req, res) {
res.sendFile(process.cwd() + "/views/index.html");
});
// Storage setup
const DB_NAME = "db.json";
const UPLOAD_PATH = "uploads";
const upload = multer({ dest: `${UPLOAD_PATH}/` });
const db = new loki(`${UPLOAD_PATH}/${DB_NAME}`, { persistenceMethod: "fs" });
// Utils
// load existing file collection or create a new one
const loadCollection = function(colName, _db) {
return new Promise(resolve => {
_db.loadDatabase({}, () => {
const _collection =
_db.getCollection(colName) || _db.addCollection(colName);
resolve(_collection);
});
});
};
// Delete existing files helper ( to avoid to many files being uploaded)
const cleanUploads = async function(folderPath) {
try {
await del.sync([`${folderPath}/**`, `!${folderPath}`]);
console.info("INFO: Cleaned all previosly uploaded files!");
} catch (e) {
console.log(e);
}
};
// API handlers
// File upload handler
const fileUploadHandler = async (req, res, next) => {
try {
const file = req.file;
const collection = await loadCollection("files", db);
const data = collection.insert(file);
db.saveDatabase();
res.status(200).json({
name: file.originalname,
type: file.mimetype,
size: file.size,
url: "/api/files/" + file.$loki
});
} catch (e) {
next(e);
}
};
// File get handler
const getFileHandler = async (req, res, next) => {
try {
const collection = await loadCollection("files", db);
if (!req.params.id) {
return res.send(collection.data);
}
const result = collection.get(req.params.id);
if (!result) return res.sendStatus(404);
res.setHeader("Content-Type", result.mimetype);
fs.createReadStream(path.join("uploads", result.filename)).pipe(res);
} catch (e) {
next(e);
}
};
// API endpoints
// Upload file
app.post("/api/fileanalyse", upload.single("upfile"), fileUploadHandler);
// Get file(s)
app.get("/api/files/:id?", getFileHandler);
app.listen(process.env.PORT || 3000, function() {
console.log("SERVER: Node.js listening on PORT:", process.env.PORT || 3000);
cleanUploads(UPLOAD_PATH);
});