Skip to content

Instantly share code, notes, and snippets.

@amane-katagiri
Last active March 29, 2026 03:01
Show Gist options
  • Select an option

  • Save amane-katagiri/2ff0d0195f2d2ed18ce6252e423fce16 to your computer and use it in GitHub Desktop.

Select an option

Save amane-katagiri/2ff0d0195f2d2ed18ce6252e423fce16 to your computer and use it in GitHub Desktop.
30秒に一回のペースで data.txt からランダムなテキストをSSEで配信する簡単なスクリプト
ひとみを のぞきこむと じぶんの すがたが みえる。だが その かおは いつも すこしだけ わらっている。
だいじな ひとを わすれた にんげんの そばに あらわれる。かおりを かぐと なぜか なみだが でるという。
いちど なかまと みとめた あいてを にどと はなさない。トレーナーが きえても その ばしょで まわりつづける。
やくそくを やぶった にんげんを さがしだす。みつけると こゆびに あかい いとを まきつけて どこかへ つれさる。
はなびらが じかんごとに いちまいずつ ちる。さいごの いちまいが ちるとき なにが おこるかは だれも しらない。
cd /d "%~dp0"
node random-words.mjs
// @ts-check
// Random words SSE Server
// Usage: node random-words.mjs
import { createServer } from "node:http";
import { readFileSync } from "node:fs";
const POLL_INTERVAL = 30_000;
const PORT = 3000;
const LIST = readFileSync("data.txt", "utf-8").split("\n").filter(Boolean);
createServer(async (req, res) => {
const url = new URL(req.url ?? "/", `http://127.0.0.1:${PORT}`);
if (url.pathname === "/") {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
"Access-Control-Allow-Origin": "*",
});
let alive = true;
req.on("close", () => {
alive = false;
});
while (alive) {
try {
const item = LIST[Math.floor(Math.random() * LIST.length)];
res.write(`data: ${item}\n\n`);
} catch (e) {
console.error("polling error:", e);
res.write("data: 情報取得に失敗しました\n\n");
}
await new Promise((r) => setTimeout(r, POLL_INTERVAL));
}
return;
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end();
}).listen(PORT, () => {
console.log(`Random words SSE Server: http://127.0.0.1:${PORT}/`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment