-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
112 lines (99 loc) · 3.64 KB
/
server.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
108
109
110
111
112
const fs = require('fs')
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const path = require('path')
const fileUpload = require('express-fileupload');
async function main() {
let router = express.Router();
let app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cors())
app.set('view engine', 'ejs')
app.use('/assets', express.static('public/assets'))
app.use('/resources', express.static('resources'))
app.use('/resonance', express.static('node_modules/resonance-audio'))
app.use(fileUpload());
router.get('/', (request, response) => {
let directoryPath = path.join(__dirname, '\\resources\\audio')
readDirectory(directoryPath).then((soundsList) => {
let renderedList = []
soundsList.forEach((sound) => {
let arr = sound.split(".")
let obj = { path: arr[0], ext: arr[1]}
renderedList.push(obj)
})
response.render("index", {"sounds": renderedList})
}).catch((err)=> {
response.status(500).json({
error: err
})
})
});
router.post('/upload', function(req, res) {
try {
if (!req.files) {
res.send({
status: false,
message: 'No file uploadedSounds'
});
} else {
let uploadedSounds = req.files.sounds;
if(!(uploadedSounds instanceof Array)){
uploadedSounds = [req.files.sounds]
}
let uploadDirectoryPath = __dirname + '\\resources\\audio\\'
readDirectory(uploadDirectoryPath).then((soundsList) => {
let promises = []
for(let i = 0; i<uploadedSounds.length; i++){
let initialName = uploadedSounds[i].name.split('.')
let extension = initialName.pop()
let id = 1
while(soundsList.includes(uploadedSounds[i].name)){
uploadedSounds[i].name = initialName +` - (${id}).` + extension
id = id + 1
}
promises.push(uploadedSounds[i].mv(uploadDirectoryPath + uploadedSounds[i].name))
}
Promise.all(promises)
.then(() => {
let soundAdded = []
uploadedSounds.forEach((sound) => {
soundAdded.push({
name : sound.name,
})
})
res.status(200).json({
status: 'success',
data : soundAdded
})
}).catch((err) => {
res.status(400).json({
status: 'failure',
error: err
})
})
})
}
}catch (err){
res.status(500).json({
status: 'failure',
error: err
})
}
})
app.use('/', router)
app.listen(8080)
}
function readDirectory(directoryPath){
return new Promise((resolve, reject) => {
fs.readdir(directoryPath, function(err, soundsList){
if(err){
reject(err)
}
resolve(soundsList)
})
})
}
main()