node-gettext is a comprehensive JavaScript implementation of a significant subset of the GNU gettext localization framework, designed for both server-side Node.js and client-side browser environments, making it an isomorphic solution. Currently at version 3.0.1, the library focuses exclusively on string and phrase translation, omitting categories like LC_NUMERIC or LC_MONETARY found in the full GNU gettext specification, as it assumes the LC_MESSAGES category at all times. It supports core gettext features such as domains, contexts, and plural forms, and ships with pluralization rules for 136 languages. A key differentiator is that developers are responsible for loading translation files (e.g., .mo, .po, .json via gettext-parser) and providing them to the instance, rather than the library automatically reading from the file system. The library provides useful error messages when debug is enabled and emits events for internal issues, such as missing translations.
npm install node-gettextVerified import paths — ran on the pinned version, not inferred.
Demonstrates basic setup, adding translations from an in-memory object, setting the active locale, and translating singular, plural, and interpolated strings. It also includes an example of handling error events for missing translations.
Review the official 'Migrating from v1 to v2' guide in the documentation to understand the necessary code modifications.
Use dedicated, robust JavaScript libraries for number, currency, date, and other locale-specific formatting needs.
In Node.js, use `fs` along with `gettext-parser` to load and parse `.mo` or `.po` files. In browser environments, fetch `.json` translation files via HTTP and then add them to the `Gettext` instance.
Always register an `on('error', handler)` listener on your `Gettext` instance to ensure all internal errors, including missing translations, are logged, displayed, or otherwise managed.Change the import statement to `import Gettext from 'node-gettext'`.
Either configure your project for ES Modules by adding `"type": "module"` to your `package.json`, or use the CommonJS `require` syntax: `const Gettext = require('node-gettext')`.Verify that `gt.addTranslations(locale, domain, translations)` has been called with the correct `locale` and `domain`, that `gt.setLocale(locale)` is correctly set, and that the translation key exactly matches a `msgid` entry in your loaded translation data. Also, ensure you handle 'error' events for debugging.