Replication: net.connect + SYNC

Same shape as Go and Python. SYNC dumps the state, then live stream. The replica is read-only.

08-replication/server.mjs
javascript
function replicate(args) {
  const payload = encodeArray(args);
  for (const r of REPLICAS) {
    if (!r.writable) { REPLICAS.delete(r); continue; }
    r.write(payload);
  }
}

Master replicates to every conn in REPLICAS. Dead conns get pruned inline.

08-replication/server.mjs
javascript
function replicaConnect() {
  const [host, p] = REPLICA_OF.split(":");
  const conn = netConnect(parseInt(p, 10), host, () => {
    conn.write(encodeArray(["SYNC"]));
  });
  let buf = Buffer.alloc(0);
  conn.on("data", (chunk) => {
    buf = Buffer.concat([buf, chunk]);
    while (true) {
      const r = parseResp(buf);
      if (r === null) break;
      buf = buf.slice(r.consumed);
      if (Array.isArray(r.value)) {
        isReplicatedWrite = true;
        try { handleCommand(r.value, conn); } finally { isReplicatedWrite = false; }
      }
    }
  });
}

Replica side: net.connect to master, send SYNC, apply incoming commands. The isReplicatedWrite flag prevents READONLY errors during apply.