-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
55 lines (42 loc) · 1.47 KB
/
server.js
File metadata and controls
55 lines (42 loc) · 1.47 KB
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
import express from 'express';
import qr from 'qr-image';
import fs from'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import bodyParser from'body-parser';
import dotenv from 'dotenv';
dotenv.config(); // Load environment variables
const app = express();
const PORT = 3000;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const qrDir = path.join(__dirname, 'generated_qr');
if (!fs.existsSync(qrDir)) {
fs.mkdirSync(qrDir, { recursive: true });
}
// Middleware
app.use(express.json()); // Required to parse JSON body
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/generated_qr', express.static(path.join(__dirname, 'generated_qr')));
// Endpoint to generate QR
app.post('/generate', (req, res) => {
const url = req.body.url;
if (!url) {
return res.status(400).json({error: 'URL is required'});
}
const fileName = `qr_${Date.now()}.png`;
const filePath = path.join(__dirname, 'generated_qr', fileName);
const qr_png = qr.image(url, { type: 'png' });
qr_png.pipe(fs.createWriteStream(filePath));
//Save the URL to txt file
fs.appendFile('url.txt', url + '\n', (err) =>{
if(err) console.error('Failed to save URL: ', err);
});
// Send back path to client
res.json({ qrUrl: `/generated_qr/${fileName}`});
});
// Start server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});