tinycodinglm / polyglot /polyglot-0001.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 16)
d517dc9 verified
|
Raw History Blame Contribute Delete
1.39 kB
opencode trace
System You are an expert software engineer. You give correct, idiomatic, runnable code with brief explanations.

You are an expert software engineer. You give correct, idiomatic, runnable code with brief explanations.

User

How do I count lines, words, characters and bytes of a UTF-8 text file? Show me the TypeScript (Node) version.

Assistant

In Node, string.length counts UTF-16 code units (emoji split in two), so spread into code points with [...s]; Buffer.byteLength gives bytes.

ts
import { writeFileSync, readFileSync } from "node:fs";

const text: string = "Olá mundo! Ação, coração.\nSegunda linha: Straße, 你好.\n";
writeFileSync("sample.txt", text, "utf8");
const data: string = readFileSync("sample.txt", "utf8");
const bytes: number = Buffer.byteLength(data, "utf8");
const chars: number = [...data].length;
const words: number = data.trim().split(/\s+/).length;
const lines: number = data.trimEnd().split("\n").length;
console.log(`lines=${lines} words=${words} chars=${chars} bytes=${bytes}`);
if (lines !== 2 || words !== 8) { throw new Error("count mismatch"); }
if (!(bytes > chars)) { throw new Error("expected multibyte content"); }