Skip to content
jshacks.dev
Node.js

Build a Log Tailing Dashboard With Node.js

Build a live log viewer in Node.js: read appended bytes by offset, handle partial lines and truncation, and stream new lines to the browser with SSE.

8 min read
Summarize in AI
Flat illustration of a magnifier over lines of a log, with the Node.js, TypeScript, npm and Vite logos.

Sooner or later you want to watch a log file from a browser tab instead of an SSH session. A log tailing dashboard does what tail -f does, and sends each new line to a web page as it is written. In Node.js it needs surprisingly little: a way to read only the bytes added since last time, a loop that checks for growth, and a streaming response. This post builds it on Node.js 26 'Lithium', the LTS line since 2026-10-28, and the code also runs on the 24 and 22 maintenance lines. The browser side uses server-sent events through EventSource, a simpler fit than WebSockets for one-way text. There are no dependencies.

How tailing actually works

A log file only grows at the end, so tailing means remembering how far you have read. The reader keeps an offset, the byte position after the last data it processed. Each check compares the file size with the offset. If the size is larger, read from the offset to the end and advance. If the size is smaller, the file was truncated or rotated, so start again from zero.

Two details make this harder than it sounds.

  • A write can end in the middle of a line. If a program wrote GET /a and flushed, then wrote 200\n a moment later, a reader that splits on newlines would show two broken fragments. The reader must hold the unfinished tail, called the carry, and prepend it to the next read.

  • Reading the whole file every time works for small logs and falls apart for a gigabyte. Reading from an offset costs only the new bytes.

The tool for positional reads is a file handle from fs/promises. Its read method takes a buffer, a length and a position, as described in the fs documentation.

Reading from an offset

The function below does one poll. It opens the file, compares sizes, reads the new bytes, and splits them into complete lines plus a carry. It returns the new offset so the caller can pass it back next time.

tail.jsJavaScript
import { open, writeFile, appendFile, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

export async function readFrom(file, offset, carry = "") {
  const handle = await open(file, "r");
  try {
    const { size } = await handle.stat();
    if (size < offset) {
      offset = 0;
      carry = "";
    }
    const length = size - offset;
    const buffer = Buffer.alloc(length);
    await handle.read(buffer, 0, length, offset);
    const parts = (carry + buffer.toString("utf8")).split("\n");
    const rest = parts.pop();
    return { lines: parts, offset: size, carry: rest };
  } finally {
    await handle.close();
  }
}

const dir = await mkdtemp(join(tmpdir(), "tail-"));
const file = join(dir, "app.log");

await writeFile(file, "a\nb\nc");
let state = await readFrom(file, 0);
console.log(JSON.stringify(state.lines), `carry="${state.carry}"`, `offset=${state.offset}`);

await appendFile(file, "d\ne\n");
state = await readFrom(file, state.offset, state.carry);
console.log(JSON.stringify(state.lines), `carry="${state.carry}"`, `offset=${state.offset}`);

await writeFile(file, "x\n");
state = await readFrom(file, state.offset, state.carry);
console.log(JSON.stringify(state.lines), `carry="${state.carry}"`, `offset=${state.offset}`);

await rm(dir, { recursive: true });

Trace the three steps. The first file content is a\nb\nc, five bytes, with no newline after c. Splitting gives a, b and c; the last part is the unfinished line, so it becomes the carry and the lines are a and b. The append adds d\ne\n, four bytes, making nine. The carry c is joined to d to give the line cd, followed by e, and the final empty string is the new carry. The third step overwrites the file with x\n, two bytes, smaller than the stored offset of nine, so the reader resets to zero and returns x.

Text
["a","b"] carry="c" offset=5
["cd","e"] carry="" offset=9
["x"] carry="" offset=2

One limitation is worth stating plainly. A multi-byte UTF-8 character can be cut in half at a read boundary, and converting a partial sequence to a string produces a replacement character. For logs that are mostly ASCII this rarely shows, but if yours contain non-Latin text, keep the carry as bytes and decode complete lines only, or use StringDecoder from node:string_decoder, which holds incomplete sequences between calls.

Rotation is a separate case

The truncation check handles copytruncate-style rotation, where the file is emptied in place. Many tools instead rename the file and create a new one under the old name. Your open handle, if you kept one, would follow the renamed file. The sample opens the path on every poll, so it picks up the new file automatically; the size comparison then catches the fact that the new file is smaller. An edge case remains: if the new file grows past the old offset between two polls, you will miss the start of it. Comparing the file's inode number from handle.stat() as well as its size detects that, and resets the offset when it changes.

Streaming to the browser

Server-sent events are a long-lived HTTP response with the text/event-stream content type. Each message is one or more data: lines followed by a blank line. The browser's EventSource reconnects on its own if the connection drops. The HTML standard defines the format.

The server polls the file on a timer and broadcasts new lines to every connected client. Polling twice a second is plenty for a dashboard and avoids the quirks of fs.watch, whose behavior differs between operating systems and on network file systems. A small ring buffer holds the last hundred lines so a new visitor sees recent history at once.

server.jsJavaScript
import { createServer } from "node:http";
import { readFrom } from "./tail.js";

const FILE = process.argv[2] ?? "app.log";
const clients = new Set();
const recent = [];

let state = { offset: 0, carry: "" };
try {
  state = await readFrom(FILE, 0);
  recent.push(...state.lines.slice(-100));
} catch (err) {
  if (err.code !== "ENOENT") throw err;
}

setInterval(async () => {
  try {
    state = await readFrom(FILE, state.offset, state.carry);
  } catch (err) {
    if (err.code === "ENOENT") return;
    throw err;
  }
  for (const line of state.lines) {
    recent.push(line);
    if (recent.length > 100) recent.shift();
    for (const res of clients) res.write(`data: ${line}\n\n`);
  }
}, 500);

const page = `<!doctype html>
<meta charset="utf-8">
<title>Logs</title>
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  new EventSource("/events").onmessage = (e) => {
    out.textContent += e.data + "\\n";
    window.scrollTo(0, document.body.scrollHeight);
  };
</script>`;

createServer((req, res) => {
  if (req.url === "/events") {
    res.writeHead(200, {
      "content-type": "text/event-stream",
      "cache-control": "no-cache",
      connection: "keep-alive",
    });
    for (const line of recent) res.write(`data: ${line}\n\n`);
    clients.add(res);
    req.on("close", () => clients.delete(res));
    return;
  }
  res.writeHead(200, { "content-type": "text/html" }).end(page);
}).listen(3000, "127.0.0.1", () => console.log("logs on http://127.0.0.1:3000"));

The page writes each line with textContent, never innerHTML. Log lines contain user input, such as request paths and error messages, and inserting them as HTML would let a crafted request execute script in your dashboard. The server binds to 127.0.0.1 so the dashboard is not exposed by accident; reach it through an authenticated proxy or an SSH tunnel.

Starting it prints one line.

Text
logs on http://127.0.0.1:3000

If the log holds boot and then the application appends first and second, curl -N http://127.0.0.1:3000/events shows each as an event, separated by a blank line. The -N flag turns off curl's output buffering so lines appear as they arrive.

Text
data: boot

data: first

data: second

Filtering and limits

A dashboard that shows everything is noisy. Add a level query parameter, parse it from req.url, and store it with the client so the broadcast loop writes only matching lines. Matching is as simple as line.includes('"level":"error"') for JSON logs. Keep the filter on the server, so clients that ask for errors do not receive every line.

Protect the server from slow clients. res.write returns false when the socket's buffer is full, and a client that never reads can make the process hold memory for it. Drop a client when its writable length passes a limit, using res.writableLength. Cap the number of clients too. And never tail a file the user chooses by name: fix the path at startup, since a ?file= parameter turns the dashboard into a file reader.

Where this dashboard stops

This is one process reading one file and pushing to a handful of browsers, a good fit for a development machine or a single small server. It keeps no history beyond a hundred lines, it cannot search old logs, and it has no authentication. Past a few services or machines, ship logs to a collector and search them there. The readFrom function remains useful anywhere you need to follow a growing file, for example in a small agent that forwards lines to that collector.

Hardening and deploying the dashboard

The demo files include a small check at the bottom of tail.js so the output can be shown. In a real project move it to a separate check file, because the server imports readFrom and would otherwise run the demo at start.

A log viewer exposes whatever your application writes, and applications write more than they should: tokens in URLs, email addresses, stack traces with file paths. Before sharing the dashboard beyond yourself, decide who may see it, and put authentication in front of it at a reverse proxy. If the proxy buffers responses, server-sent events appear in bursts or not at all; disable buffering for the /events path, and send a comment line such as : ping every thirty seconds, since idle connections are closed by many proxies.

Redaction is better done at the source than at the dashboard, but a last filter on the server is cheap insurance. Replace anything that looks like a bearer token or a long hex string before writing a line to clients. Treat it as a safety net, not a guarantee.

Think about volume too. A busy service can write thousands of lines per second, and sending every one to a browser tab will freeze the tab. Batch lines into one event every few hundred milliseconds, cap the number of lines kept in the page by removing the oldest, and let the user pause the stream. The ring buffer on the server already bounds memory there, and the same idea applies in the page.

Last, remember the process model. The polling timer runs in one process for all clients, which is efficient. If you run several instances behind a balancer, each one tails its own local file, so a viewer sees only the instance it reached. For many machines, a central collector is the sound design.

Share

Keep reading

Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, RabbitMQ, Apache Kafka, Redis and npm logos.
Node.js

What Is Node.js, and What Is It Good At?

Node.js runs JavaScript outside the browser on the V8 engine. Learn what it is, how its event loop works, where it shines, and where another tool fits better.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.