Files
shopApiNg/server.js

53 lines
1.7 KiB
JavaScript

import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs/promises';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export function startServer() {
const app = express();
const PORT = process.env.SERVER_PORT || 3000;
const HOST = process.env.SERVER_HOST || '0.0.0.0';
const CACHE_DIR = process.env.CACHE_LOCATION || './cache';
// Serve category tree JSON
app.get('/api/categories', async (req, res) => {
try {
const treePath = path.join(CACHE_DIR, 'category_tree.json');
const data = await fs.readFile(treePath, 'utf-8');
res.json(JSON.parse(data));
} catch (err) {
res.status(500).json({ error: 'Failed to load category tree' });
}
});
// Serve category images
app.get('/img/cat/:id.avif', (req, res) => {
const { id } = req.params;
const imagePath = path.join(CACHE_DIR, 'img', 'categories', `${id}.avif`);
res.sendFile(path.resolve(imagePath), (err) => {
if (err) {
res.status(404).send('Image not found');
}
});
});
// Serve index.html
app.get('/', (req, res) => {
const htmlPath = path.join(__dirname, 'index.html');
console.log('Attempting to serve:', htmlPath);
res.sendFile(htmlPath, (err) => {
if (err) {
console.error('Error serving index.html:', err);
res.status(500).send('Error loading page');
}
});
});
app.listen(PORT, HOST, () => {
console.log(`🌐 Server running on http://${HOST}:${PORT}`);
});
}