File size: 1,394 Bytes
d517dc9
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "polyglot-0001", "name": "UTF-8 file stats in TypeScript"}
{"type": "message", "message": {"role": "system", "content": "You are an expert software engineer. You give correct, idiomatic, runnable code with brief explanations."}}
{"type": "message", "message": {"role": "user", "content": "How do I count lines, words, characters and bytes of a UTF-8 text file? Show me the TypeScript (Node) version."}}
{"type": "message", "message": {"role": "assistant", "content": "In Node, `string.length` counts UTF-16 code units (emoji split in two), so spread into code points with `[...s]`; `Buffer.byteLength` gives bytes.\n\n```ts\nimport { writeFileSync, readFileSync } from \"node:fs\";\n\nconst text: string = \"Olá mundo! Ação, coração.\\nSegunda linha: Straße, 你好.\\n\";\nwriteFileSync(\"sample.txt\", text, \"utf8\");\nconst data: string = readFileSync(\"sample.txt\", \"utf8\");\nconst bytes: number = Buffer.byteLength(data, \"utf8\");\nconst chars: number = [...data].length;\nconst words: number = data.trim().split(/\\s+/).length;\nconst lines: number = data.trimEnd().split(\"\\n\").length;\nconsole.log(`lines=${lines} words=${words} chars=${chars} bytes=${bytes}`);\nif (lines !== 2 || words !== 8) { throw new Error(\"count mismatch\"); }\nif (!(bytes > chars)) { throw new Error(\"expected multibyte content\"); }\n```"}}