Skip to content

Instantly share code, notes, and snippets.

@nanonull
Created January 12, 2024 14:12
Show Gist options
  • Save nanonull/0d7d63d3dde118a601157368b4d3b606 to your computer and use it in GitHub Desktop.
Save nanonull/0d7d63d3dde118a601157368b4d3b606 to your computer and use it in GitHub Desktop.
Simple express server to expose files in local FS
const express = require('express');
const path = require('path');
const fs = require('fs');
const cors = require('cors');
const util = require('util');
const fspro = require('fs').promises;
const app = express();
const PORT = 3000;
app.use(cors());
app.use(express.static(path.join(__dirname, '.')));
app.get('/api/test', (req, res) => {
const data = { message: 'Hello from the server!' };
res.json(data);
});
app.get('/api/dirs', (req, res) => {
const currentDir = __dirname;
fs.readdir(currentDir, (err, files) => {
if (err) {
console.error('Error reading directory:', err);
res.status(500).json({ error: 'Internal Server Error' });
return;
}
const dirs = files.filter(file => fs.statSync(path.join(currentDir, file)).isDirectory());
const data = { dirs: dirs };
res.json(data);
});
});
// API endpoint to get an array of JSON stats data from a specific run directory
app.get('/api/stats/:rundir', async (req, res) => {
try {
const rundir = req.params.rundir;
const runStatsFiles = await getRunStatsFiles(rundir);
const jsonDataArray = await Promise.all(runStatsFiles.map(async (file) => {
const filePath = path.join(__dirname, rundir, file);
console.log('filePath=' + filePath)
const data = await fspro.readFile(filePath, { encoding: 'utf-8' });
return JSON.parse(data);
}));
res.json(jsonDataArray);
} catch (error) {
console.error('Error fetching JSON stats data:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
const readdir = util.promisify(fs.readdir);
async function getRunStatsFiles(rundir) {
try {
const dirPath = path.join(__dirname, rundir);
console.log('dirPath=' + dirPath)
if (!fs.existsSync(dirPath)) {
console.error('Run directory does not exist:', dirPath);
return [];
}
const files = await readdir(dirPath);
const statsFiles = files.filter(file => file.startsWith('run_stats_stage_') && file.endsWith('.json'));
return statsFiles;
} catch (error) {
console.error('Error reading run directory:', error);
throw error;
}
}
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment