-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
107 lines (86 loc) · 2.65 KB
/
index.js
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
require('dotenv').config();
const path = require('path');
const url = require('url');
const fg = require('fast-glob');
const fs = require('fs');
const mime = require('mime-types');
const cors = require('cors');
const express = require('express');
const app = express();
const port = process.env.PORT;
const UploadsDir = path.join(__dirname, 'storage/uploads');
function fullUrl(req) {
return url.format({
protocol: req.protocol,
host: req.get('host'),
pathname: req.originalUrl
});
}
app.use(cors({ origin: true }));
app.use(express.static('public'));
// app.engine('.ejs', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.get('/', function(req, res) {
res.render('layout');
});
app.get('/uploads', async function(req, res) {
const data = await fg('*.*', { cwd: UploadsDir });
res.json({ success: true, data });
});
app.get('/uploads/:filename', function(req, res) {
const filename = req.params.filename;
if(filename) {
const filepath = path.join(UploadsDir, filename);
const mimetype = mime.lookup(filename);
const stream = fs.createReadStream(filepath);
stream.on('open', function() {
res.set('Content-Type', mimetype);
stream.pipe(res);
});
stream.on('error', function() {
res.status(404).render('error', { statusCode: 404 });
});
} else {
res.status(404).render('error', { statusCode: 404 });
}
});
app.put('/uploads/:filename', async function(req, res) {
let filename = req.params.filename;
if(filename) {
const filepath = path.join(UploadsDir, filename);
let exists = false;
try {
await fs.stat(filepath);
exists = true;
} catch(err) {}
if(exists) {
res.status(409).json({ success: false });
} else {
const stream = fs.createWriteStream(filepath);
stream.on('close', function() {
res.json({ success: true });
});
req.pipe(stream);
}
} else {
res.status(409).json({ success: false });
}
});
app.delete('/uploads/:filename', async function(req, res) {
let filename = req.params.filename;
if(filename) {
const filepath = path.join(UploadsDir, filename);
fs.unlink(filepath, err => {
if(err) {
res.status(409).json({ success: false });
} else {
res.json({ success: true });
}
});
} else {
res.status(409).json({ success: false });
}
});
app.get("*", (_, res) => res.status(404).json({ success: false, data: "Endpoint not found" }));
app.listen(port, () => console.log(`Listening on port ${port}!`));