-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
66 lines (54 loc) · 1.74 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
const express = require("express")
const multer = require("multer")
const fs = require("fs")
const path = require("path")
const { exec } = require("child_process")
const { stdout, stderr } = require("process")
const app = express()
app.use(express.static("public"))
const PORT = process.env.PORT || 5000
const dir = "public"
const subDir = "public/uploads"
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir)
// why both are same? because subDir is "public/uploads"
fs.mkdirSync(subDir)
}
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, subDir)
},
filename: function (req, file, cb) {
cb(null, file.fieldname + "-" + Date.now() + path.extname(file.originalname))
}
})
const upload = multer({ storage: storage })
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html")
})
// single("file") => "file" came from name attribute of the html input form
app.post("/convert", upload.single("file"), (req, res) => {
if (req.file) {
console.log(req.file.path);
const output = Date.now() + "-" + "convertedAudio.mp3"
exec(`ffmpeg -i ${req.file.path} ${output}`, (error, stdout, stderr) => {
if (error) {
console.log(`Convert Error: ${error}`);
return
} else {
console.log("File is converted");
res.download(output, (error) => {
if (error) {
throw error
} else {
fs.unlinkSync(req.file.path)
fs.unlinkSync(output)
}
})
}
})
}
})
app.listen(PORT, () => {
console.log("Server: http://localhost:5000");
})