server-text-width is a utility library designed for server-side environments, specifically Node.js, to accurately calculate the pixel width of text. Unlike browser-based solutions that leverage Canvas or DOM elements, this package operates without a browser environment by relying on pre-generated lookup tables. This capability is crucial for server-side rendering (SSR) scenarios where text needs to be trimmed, aligned, or used in layout calculations without client-side dependencies. The current stable version is 1.0.2, indicating a nascent but stable 1.x release series. Its key differentiators include zero runtime dependencies, full Unicode support, compatibility with custom fonts, and a highly compact base64 encoding for character width data. Developers must use an included `mappingTool.html` to generate these character width lookup tables for their specific fonts, sizes, and weights, which are then passed to the library's `init` function. This approach ensures consistent text measurement results across environments and allows for precise control over font metrics.
npm install server-text-widthVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to initialize the `server-text-width` library with a pre-generated lookup table and then use the `getTextWidth` function to calculate the pixel width of various strings with specified font styles. It highlights the manual setup required for the lookup table.
Ensure you open `mappingTool.html`, configure the desired fonts and character ranges, and copy the generated `TEXT_WIDTH_LOOKUP_TABLE` constant into your application code.
When using `mappingTool.html`, carefully select all necessary Unicode ranges (e.g., Latin, Cyrillic, CJK) to ensure full character coverage for your application's expected text inputs.
Generate separate lookup tables for each font/size/weight combination using `mappingTool.html` and then manually combine them into a single object in your application code, using unique keys for each configuration.
Verify that `TEXT_WIDTH_LOOKUP_TABLE` contains valid, non-empty data generated by `mappingTool.html`, and that the `fontString` parameter in `getTextWidth(text, fontString)` exactly matches a key present in your lookup table (e.g., 'Arial|16px|normal').
Update your import statement from `const { init } = require('server-text-width');` to `import { init } from 'server-text-width';` and ensure your project's `package.json` specifies `"type": "module"` or uses `.mjs` extensions for ESM files.Re-generate your `TEXT_WIDTH_LOOKUP_TABLE` using `mappingTool.html`, making sure to select all relevant Unicode character ranges and exactly match the font name, size, and weight you intend to use in `getTextWidth()`.
No dependency data recorded yet.