-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (51 loc) · 1.7 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
const express = require('express');
const multer = require('multer');
const ffmpeg = require('fluent-ffmpeg');
const path = require('path');
const fs = require('fs');
const dotenv = require('dotenv')
dotenv.config()
const app = express();
const port = process.env.PORT;
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
const extension = path.extname(file.originalname);
cb(null, file.fieldname + '-' + uniqueSuffix + extension);
}
});
const upload = multer({ storage: storage });
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.post('/convert', upload.single('image'), (req, res) => {
const inputFilePath = req.file.path;
const outputFilePath = path.join('uploads', `${Date.now()}.webp`);
ffmpeg(inputFilePath)
.output(outputFilePath)
.outputOptions([
'-c:v libwebp',
'-lossless 1',
'-q:v 100',
'-compression_level 6'
])
.on('end', () => {
fs.unlinkSync(inputFilePath);
res.json({
imageUrl: `/uploads/${path.basename(outputFilePath)}`,
downloadUrl: `/uploads/${path.basename(outputFilePath)}`
});
})
.on('error', err => {
console.error('Error during conversion:', err);
res.status(500).send('Error during conversion');
})
.run();
});
app.use('/uploads', express.static('uploads'));
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});