Research
Security News
Malicious npm Package Targets Solana Developers and Hijacks Funds
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
node-gettext
Advanced tools
node-gettext is a JavaScript library that provides internationalization (i18n) and localization (l10n) functionalities. It allows developers to manage translations and localize their applications by using GNU gettext style .po and .mo files.
Loading Translations
This feature allows you to load translation files into the node-gettext instance. The example demonstrates how to read a .po file and add it to the gettext instance under a specific domain.
const Gettext = require('node-gettext');
const fs = require('fs');
const gt = new Gettext();
const translations = fs.readFileSync('path/to/your/translation/file.po');
gt.addTextdomain('your_domain', translations);
Translating Strings
This feature allows you to translate strings using the loaded translations. The example shows how to translate the string 'Hello, world!' using the gettext instance.
const translatedString = gt.gettext('Hello, world!');
console.log(translatedString);
Setting Locale
This feature allows you to set the locale for translations. The example demonstrates how to set the locale to Spanish ('es') and then translate the string 'Hello, world!'.
gt.setLocale('es');
const translatedString = gt.gettext('Hello, world!');
console.log(translatedString);
Plural Forms
This feature allows you to handle plural forms in translations. The example shows how to translate singular and plural forms of a string based on the count.
const singular = gt.ngettext('%d apple', '%d apples', 1);
const plural = gt.ngettext('%d apple', '%d apples', 2);
console.log(singular);
console.log(plural);
i18next is a popular internationalization framework for JavaScript. It provides a comprehensive solution for managing translations and supports various backends for loading translations. Compared to node-gettext, i18next offers more flexibility and a wider range of features, including support for nested translations, interpolation, and more.
Polyglot is a lightweight internationalization library for JavaScript. It provides a simple API for managing translations and supports basic pluralization. While it is easier to use and integrate compared to node-gettext, it lacks some of the advanced features and flexibility offered by node-gettext.
MessageFormat is a library for handling both pluralization and gender in translations. It uses ICU MessageFormat syntax, which is more powerful and expressive than the GNU gettext format used by node-gettext. However, it may have a steeper learning curve due to its more complex syntax.
node-gettext
is a JavaScript implementation of (a large subset of) gettext, a localization framework originally written in C.
If you just want to parse or compile mo/po files, for use with this library or elsewhere, check out gettext-parser.
NOTE: This is the README for v2 of node-gettext, which introduces several braking changes. You can find the README for v1 here.
debug
optionThere are two main differences between node-gettext
and GNU's gettext:
LC_MESSAGES
, LC_NUMERIC
and LC_MONETARY
, but since there already is a plethora of great JavaScript libraries to deal with numbers, currencies, dates etc, node-gettext
is simply targeted towards strings/phrases. You could say it just assumes the LC_MESSAGES
category at all times.bindtextdomain(domain, localesDirPath)
and setlocale(category, locale)
, where these four parameters combined are used to read the appropriate translations file.However, since node-gettext
needs to work both on the server in web browsers (which usually is referred to as it being universal or isomorphic JavaScript), it is up to the developer to read translation files from disk or somehow provide it with translations as pure JavaScript objects using addTranslations(locale, domain, translations)
.
bindtextdomain
will be provided as an optional feature in a future release.
npm install --save node-gettext
import Gettext from 'node-gettext'
import swedishTranslations from './translations/sv-SE.json'
const gt = new Gettext()
gt.addTranslations('sv-SE', 'messages', swedishTranslations)
gt.setLocale('sv-SE')
gt.gettext('The world is a funny place')
// -> "Världen är en underlig plats"
// Add translations etc...
gt.on('error', error => console.log('oh nose', error))
gt.gettext('An unrecognized message')
// -> 'oh nose', 'An unrecognized message'
node-gettext
expects all translations to be in the format specified by gettext-parser
. Therefor, you should use that to parse .mo or .po files.
Here is an example where we read a bunch of translation files from disk and add them to our Gettext
instance:
import fs from 'fs'
import path from 'path'
import Gettext from 'node-gettext'
import { po } from 'gettext-parser'
// In this example, our translations are found at
// path/to/locales/LOCALE/DOMAIN.po
const translationsDir = 'path/to/locales'
const locales = ['en', 'fi-FI', 'sv-SE']
const domain = 'messages'
const gt = new Gettext()
locales.forEach((locale) => {
const fileName = `${domain}.po`
const translationsFilePath = path.join(translationsDir, locale, fileName)
const translationsContent = fs.readFileSync(translationsFilePath)
const parsedTranslations = po.parse(translationsContent)
gt.addTranslations(locale, domain, parsedTranslations)
})
String
String
String
String
String
String
String
String
Creates and returns a new Gettext instance.
Returns: Object
- A Gettext instance
Params
[options]
: Object
- A set of options
.sourceLocale
: String
- The locale that the source code and its texts are written in. Translations for this locale is not necessary..debug
: Boolean
- Whether to output debug info into the
console.Adds an event listener.
Params
eventName
: String
- An event namecallback
: function
- An event handler functionRemoves an event listener.
Params
eventName
: String
- An event namecallback
: function
- A previously registered event handler functionStores a set of translations in the set of gettext catalogs.
Params
locale
: String
- A locale stringdomain
: String
- A domain nametranslations
: Object
- An object of gettext-parser JSON shapeExample
gt.addTranslations('sv-SE', 'messages', translationsObject)
Sets the locale to get translated messages for.
Params
locale
: String
- A localeExample
gt.setLocale('sv-SE')
Sets the default gettext domain.
Params
domain
: String
- A gettext domain nameExample
gt.setTextDomain('domainname')
String
Translates a string using the default textdomain
Returns: String
- Translation or the original string if no translation was found
Params
msgid
: String
- String to be translatedExample
gt.gettext('Some text')
String
Translates a string using a specific domain
Returns: String
- Translation or the original string if no translation was found
Params
domain
: String
- A gettext domain namemsgid
: String
- String to be translatedExample
gt.dgettext('domainname', 'Some text')
String
Translates a plural string using the default textdomain
Returns: String
- Translation or the original string if no translation was found
Params
msgid
: String
- String to be translated when count is not pluralmsgidPlural
: String
- String to be translated when count is pluralcount
: Number
- Number count for the pluralExample
gt.ngettext('One thing', 'Many things', numberOfThings)
String
Translates a plural string using a specific textdomain
Returns: String
- Translation or the original string if no translation was found
Params
domain
: String
- A gettext domain namemsgid
: String
- String to be translated when count is not pluralmsgidPlural
: String
- String to be translated when count is pluralcount
: Number
- Number count for the pluralExample
gt.dngettext('domainname', 'One thing', 'Many things', numberOfThings)
String
Translates a string from a specific context using the default textdomain
Returns: String
- Translation or the original string if no translation was found
Params
msgctxt
: String
- Translation contextmsgid
: String
- String to be translatedExample
gt.pgettext('sports', 'Back')
String
Translates a string from a specific context using s specific textdomain
Returns: String
- Translation or the original string if no translation was found
Params
domain
: String
- A gettext domain namemsgctxt
: String
- Translation contextmsgid
: String
- String to be translatedExample
gt.dpgettext('domainname', 'sports', 'Back')
String
Translates a plural string from a specific context using the default textdomain
Returns: String
- Translation or the original string if no translation was found
Params
msgctxt
: String
- Translation contextmsgid
: String
- String to be translated when count is not pluralmsgidPlural
: String
- String to be translated when count is pluralcount
: Number
- Number count for the pluralExample
gt.npgettext('sports', 'Back', '%d backs', numberOfBacks)
String
Translates a plural string from a specifi context using a specific textdomain
Returns: String
- Translation or the original string if no translation was found
Params
domain
: String
- A gettext domain namemsgctxt
: String
- Translation contextmsgid
: String
- String to be translatedmsgidPlural
: String
- If no translation was found, return this on count!=1count
: Number
- Number count for the pluralExample
gt.dnpgettext('domainname', 'sports', 'Back', '%d backs', numberOfBacks)
C-style alias for setTextDomain
C-style alias for setLocale
Deprecated
This function will be removed in the final 2.0.0 release.
Version 1 of node-gettext
confused domains with locales, which version 2 has corrected. node-gettext
also no longer parses files or file paths for you, but accepts only ready-parsed JSON translation objects.
Here is a full list of all breaking changes:
textdomain(domain)
is now setLocale(locale)
dgettext
, dngettext
, dpgettext
and dnpgettext
does not treat the leading domain
argument as a locale, but as a domain. To get a translation from a certain locale you need to call setLocale(locale)
beforehand.setTextDomain(domain)
has been introducedaddTextdomain(domain, file)
is now addTranslations(locale, domain, translations)
addTranslations(locale, domain, translations)
only accepts a JSON object with the shape described in the gettext-parser
README. To load translations from .mo or .po files, use gettext-parser, and it will provide you with valid JSON objects._currentDomain
is now domain
domains
is now catalogs
__normalizeDomain(domain)
has been replaced by a static method Gettext.getLanguageCode(locale)
MIT
FAQs
A JavaScript implementation of gettext, a localization framework
The npm package node-gettext receives a total of 116,017 weekly downloads. As such, node-gettext popularity was classified as popular.
We found that node-gettext demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.