• Stars
    star
    188
  • Rank 205,563 (Top 5 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 13 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A JavaScript implementation of gettext, a localization framework.

node-gettext

Build Status npm version

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.

Features

  • Supports domains, contexts and plurals
  • Supports .json, .mo and .po files with the help of gettext-parser
  • Ships with plural forms for 136 languages
  • Change locale or domain on the fly
  • Useful error messages enabled by a debug option
  • Emits events for internal errors, such as missing translations

Differences from GNU gettext

There are two main differences between node-gettext and GNU's gettext:

  1. There are no categories. GNU gettext features categories such as 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.
  2. You have to read translation files from the file system yourself. GNU gettext is a C library that reads files from the file system. This is done using 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.

Installation

npm install --save node-gettext

Usage

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"

Error events

// Add translations etc...

gt.on('error', error => console.log('oh nose', error))
gt.gettext('An unrecognized message')
// -> 'oh nose', 'An unrecognized message'

Recipes

Load and add translations from .mo or .po files

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)
})

API

Gettext

new Gettext([options])

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.

gettext.on(eventName, callback)

Adds an event listener.

Params

  • eventName: String - An event name
  • callback: function - An event handler function

gettext.off(eventName, callback)

Removes an event listener.

Params

  • eventName: String - An event name
  • callback: function - A previously registered event handler function

gettext.addTranslations(locale, domain, translations)

Stores a set of translations in the set of gettext catalogs.

Params

  • locale: String - A locale string
  • domain: String - A domain name
  • translations: Object - An object of gettext-parser JSON shape

Example

gt.addTranslations('sv-SE', 'messages', translationsObject)

gettext.setLocale(locale)

Sets the locale to get translated messages for.

Params

  • locale: String - A locale

Example

gt.setLocale('sv-SE')

gettext.setTextDomain(domain)

Sets the default gettext domain.

Params

  • domain: String - A gettext domain name

Example

gt.setTextDomain('domainname')

gettext.gettext(msgid) โ‡’ 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 translated

Example

gt.gettext('Some text')

gettext.dgettext(domain, msgid) โ‡’ 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 name
  • msgid: String - String to be translated

Example

gt.dgettext('domainname', 'Some text')

gettext.ngettext(msgid, msgidPlural, count) โ‡’ 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 plural
  • msgidPlural: String - String to be translated when count is plural
  • count: Number - Number count for the plural

Example

gt.ngettext('One thing', 'Many things', numberOfThings)

gettext.dngettext(domain, msgid, msgidPlural, count) โ‡’ 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 name
  • msgid: String - String to be translated when count is not plural
  • msgidPlural: String - String to be translated when count is plural
  • count: Number - Number count for the plural

Example

gt.dngettext('domainname', 'One thing', 'Many things', numberOfThings)

gettext.pgettext(msgctxt, msgid) โ‡’ 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 context
  • msgid: String - String to be translated

Example

gt.pgettext('sports', 'Back')

gettext.dpgettext(domain, msgctxt, msgid) โ‡’ 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 name
  • msgctxt: String - Translation context
  • msgid: String - String to be translated

Example

gt.dpgettext('domainname', 'sports', 'Back')

gettext.npgettext(msgctxt, msgid, msgidPlural, count) โ‡’ 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 context
  • msgid: String - String to be translated when count is not plural
  • msgidPlural: String - String to be translated when count is plural
  • count: Number - Number count for the plural

Example

gt.npgettext('sports', 'Back', '%d backs', numberOfBacks)

gettext.dnpgettext(domain, msgctxt, msgid, msgidPlural, count) โ‡’ 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 name
  • msgctxt: String - Translation context
  • msgid: String - String to be translated
  • msgidPlural: String - If no translation was found, return this on count!=1
  • count: Number - Number count for the plural

Example

gt.dnpgettext('domainname', 'sports', 'Back', '%d backs', numberOfBacks)

gettext.textdomain()

C-style alias for setTextDomain

See: Gettext#setTextDomain

gettext.setlocale()

C-style alias for setLocale

See: Gettext#setLocale

gettext.addTextdomain()

Deprecated

This function will be removed in the final 2.0.0 release.

Migrating from v1 to v2

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.
  • A new setTextDomain(domain) has been introduced
  • addTextdomain(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
  • The instance method __normalizeDomain(domain) has been replaced by a static method Gettext.getLanguageCode(locale)

License

MIT

See also

  • gettext-parser - Parsing and compiling gettext translations between .po/.mo files and JSON
  • lioness โ€“ Gettext library for React
  • react-gettext-parser - Extracting gettext translatable strings from JS(X) code
  • narp - Workflow CLI tool that syncs translations between your app and Transifex

More Repositories

1

react-player-controls

โฏ Dumb and (re)useful React components for media players.
JavaScript
191
star
2

react-spotify-player

Spotify player widget in React
JavaScript
42
star
3

lioness

๐Ÿฏ A React library for efficiently implementing Gettext localization
JavaScript
29
star
4

osc-debugger

A simple but charming OSC debugging tool for the terminal
JavaScript
23
star
5

use-yarn-instead

Prompts developers to use yarn instead of npm
JavaScript
21
star
6

howler-plugin-effect-chain

Adds an audio effect chain to Howler
JavaScript
18
star
7

super-tiny-wave-decoder

๐Ÿ“ป A super tiny WAVE parser and decoder, without any dependencies or unnecessary abstraction layers
JavaScript
9
star
8

multitrack-audio-element

A JavaScript (and HTML5) audio object that supports synchronized multitrack playback and streaming
JavaScript
8
star
9

transifex-api-es6

A promise-based Transifex API client for node, written in es6
JavaScript
7
star
10

dash-mpd-parser

(Alpha) MPD fetcher + parser, extracted from dash.js
JavaScript
4
star
11

pineapple-lang

An abstract, English-looking programming language for controlling real-time audio
Python
3
star
12

audio-param-shim

An AudioParam shim that lets you act on value changes in any way you want
JavaScript
3
star
13

rekuest

A functional style HTTP request composer
JavaScript
2
star
14

guess-id3

Extracts artist name and song title from filenames and writes them as ID3 to those files
JavaScript
2
star
15

follow-your-wild-dreams

1
star
16

carnival1-video-processing

Toolkit for generating videos from Kinect captured .obj frames using Processing
Processing
1
star
17

babel-plugin-snoretify

A little bit of Snรถret in your build pipeline
JavaScript
1
star
18

snappy-react-scroll-paginator

๐Ÿ“– A simple, snappy, nifty and composable scroll paginator library for React
JavaScript
1
star
19

babel-plugin-react-gettext-parser

Babel plugin for react-gettext-parser
JavaScript
1
star
20

pineapple-runtime

Run-time environment for controlling Ableton Live sets via pineapple
Python
1
star
21

Max4Live-OSC-Receiver

A Max4Live plugin that maps incoming OSC messages to device parameters
1
star
22

knitting

Generative knitting patterns in the terminal
JavaScript
1
star
23

custom-audio-node-connect

๐Ÿ”Œ A tiny module that allows you to connect custom audio nodes in your Web Audio API audio chain
JavaScript
1
star
24

good-guy-caret

Good Guy Caret helps you create carets for your React tooltips and other things ๐Ÿ”บ๐Ÿ”ป
JavaScript
1
star