-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
83 lines (67 loc) · 1.88 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
const express = require("express");
const app = express();
const port = process.env.PORT || 3000;
const router = express.Router();
const fileUpload = require("express-fileupload");
const uploadPath = __dirname + "/www/files";
const fs = require("fs");
const path = require("path");
//Middlewares
app.set("view engine", "ejs");
app.use(
fileUpload({
limits: { fileSize: 5 * 1024 * 1024 },
})
);
router.get("/", function (req, res) {
res.sendFile(path.join(__dirname + "/www/index.html"));
});
app.use(express.static(__dirname + "/www"));
app.get("/", (req, res) => {
res.render(__dirname + "/www/index");
// res.sendFile(__dirname + "/www/index.html");
});
app.post("/", (req, res) => {
if (!req.files || Object.keys(req.files).length === 0) {
return renderError(res, 400, "No files were uploaded.");
}
audioFile = req.files.audio;
const timeStamp = new Date().getTime();
const file = `${uploadPath}/${timeStamp}.webm`;
if (audioFile.mimetype !== "audio/webm") {
return renderError(res, 400, "Invalid file type.");
}
audioFile.mv(file, function (err) {
//
if (err) {
return renderError(res, 400, "Error uploading file.", err);
}
return res.json({
status: true,
message: "File uploaded",
});
});
});
app.get("/files", (req, res) => {
let directoryPath = __dirname + "/www/files";
fs.readdir(directoryPath, function (err, files) {
//handling error
if (err) {
return renderError(res, 400, "Error reading directory.", err);
}
let audioFiles = files.filter((file) => {
return path.extname(file).toLowerCase() === ".webm";
});
console.log(audioFiles);
res.render(__dirname + "/www/files", { audioFiles });
});
});
const renderError = (res, code, message, err) => {
res.status(400).json({
status: false,
message,
err,
});
};
app.listen(port);
console.log("Running at " + port);