test-01/node-page/app.js

30 lines
879 B
JavaScript

import express from 'express';
import { readFile } from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
const app = express();
const PORT = 3000;
// Helper variables for __dirname equivalent in ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Serve static files from the "public" directory
app.use(express.static(path.join(__dirname, 'public')));
// Endpoint to get the list of users
app.get('/api/users', async (req, res) => {
try {
const data = await readFile(path.join(__dirname, 'users.json'), 'utf8');
const users = JSON.parse(data);
res.json(users);
} catch (err) {
res.status(500).send('Error reading user data');
}
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});