Spaces:
Sleeping
Sleeping
| // server.js β write-access tester | |
| import express from 'express'; | |
| import fs from 'fs'; | |
| import fsp from 'fs/promises'; | |
| import path from 'path'; | |
| const PORT = process.env.PORT || 7860; | |
| const DIR = '/data'; // Space-persistent volume | |
| const FILE = path.join(DIR, 'test.txt'); | |
| const app = express(); | |
| app.use(express.json()); | |
| /* POST /write -> attempts three save methods */ | |
| app.post('/write', async (_req, res) => { | |
| const report = {}; | |
| // ensure /data exists | |
| try { | |
| fs.mkdirSync(DIR, { recursive: true }); | |
| report.mkdir = 'ok'; | |
| } catch (e) { | |
| report.mkdir = e.message; | |
| } | |
| /* ---- Method A: sync write ---- */ | |
| try { | |
| fs.writeFileSync(FILE, 'sync write\n', { flag: 'a' }); | |
| report.sync = 'ok'; | |
| } catch (e) { | |
| report.sync = e.message; | |
| } | |
| /* ---- Method B: fs.promises ---- */ | |
| try { | |
| await fsp.writeFile(FILE, 'promises write\n', { flag: 'a' }); | |
| report.promise = 'ok'; | |
| } catch (e) { | |
| report.promise = e.message; | |
| } | |
| /* ---- Method C: stream ---- */ | |
| try { | |
| await new Promise((resolve, reject) => { | |
| const stream = fs.createWriteStream(FILE, { flags: 'a' }); | |
| stream.on('error', reject); | |
| stream.end('stream write\n', resolve); | |
| }); | |
| report.stream = 'ok'; | |
| } catch (e) { | |
| report.stream = e.message; | |
| } | |
| res.json(report); | |
| }); | |
| /* GET /read -> returns file contents or error */ | |
| app.get('/read', (req, res) => { | |
| try { | |
| const txt = fs.readFileSync(FILE, 'utf-8'); | |
| res.type('text/plain').send(txt); | |
| } catch (e) { | |
| res.status(500).send(e.message); | |
| } | |
| }); | |
| app.listen(PORT, '0.0.0.0', () => | |
| console.log(`π Write-test server listening on ${PORT} (DIR=${DIR})`) | |
| ); | |