-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
39 lines (29 loc) · 1.03 KB
/
app.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
const express = require("express");
const fs = require("fs");
const path = require("path");
const app = express();
const imageDir = path.join(__dirname, "images");
app.get("/", (req, res) => {
res.send("Welcome to the Random Image Generator!");
});
app.get("/meow.png", (req, res) => {
fs.readdir(imageDir, (err, files) => {
if (err) {
console.error("Error reading directory:", err);
return res.status(500).send("Error reading directory");
}
const imageFiles = files.filter(file => {
return file.toLowerCase().endsWith(".jpg") || file.toLowerCase().endsWith(".png");
});
if (imageFiles.length === 0) {
return res.status(404).send("No images found");
}
const randomIndex = Math.floor(Math.random() * imageFiles.length);
const randomImage = path.join(imageDir, imageFiles[randomIndex]);
res.sendFile(randomImage);
});
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});