/** * diary-server.js * localhost:2626 で常時待機する軽量デーモン。 * posimai-log のダイアリーパネルから diary.md を読み書きする。 * Usage: npm run serve */ import http from 'http'; import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const DIARY_FILE = path.join(__dirname, '../diary.md'); const PORT = 2626; const server = http.createServer((req, res) => { // localhost 専用サーバーなので CORS はワイルドカードで問題なし res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; } // GET /diary → diary.md の内容を返す if (req.url === '/diary' && req.method === 'GET') { const content = fs.existsSync(DIARY_FILE) ? fs.readFileSync(DIARY_FILE, 'utf8') : ''; res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ content })); return; } // POST /diary → diary.md に上書き保存 if (req.url === '/diary' && req.method === 'POST') { let body = ''; req.on('data', chunk => { body += chunk; }); req.on('end', () => { try { const { content } = JSON.parse(body); fs.writeFileSync(DIARY_FILE, content ?? '', 'utf8'); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ ok: true })); } catch { res.writeHead(400); res.end(); } }); return; } res.writeHead(404); res.end(); }); server.listen(PORT, '127.0.0.1', () => { console.log(`[diary-server] http://localhost:${PORT} ready`); console.log(`[diary-server] diary -> ${DIARY_FILE}`); });