njs-translate
v1.0.0
Published
Lightweight, zero-dependency Node.js library for translating text via Google Translate — no API key required. Supports any language pair, batch translation, and CLI usage.
Downloads
49
Maintainers
Readme
njs-translate
A lightweight, zero-dependency Node.js library for translating text via Google Translate — no API key required.
Supports any source language, any number of target languages, batch translation of multiple strings, and ships with a built-in CLI. Written in TypeScript and distributed as both CommonJS and ESM.
Features
- No API key — uses Google Translate's public endpoint, just like your browser does
- Auto language detection — pass
"auto"as source and Google detects the language - Any language pair — source → any number of targets in a single call
- Batch translation — translate multiple texts at once with
translateBatch() - Configurable error handling — fall back silently, or throw a typed
TranslationError - Rate-limit friendly — configurable per-request delay built in
- CLI included —
njs-translate "Hello" --to bg,de,frright from your terminal - Zero runtime dependencies — nothing bundled in the programmatic API
- TypeScript-first — full type definitions included, dual CJS + ESM output
Requirements
- Node.js 18 or later (uses native
fetch— no polyfill needed)
Installation
npm install njs-translateFor global CLI access:
npm install -g njs-translateQuick Start
ESM (TypeScript / Node.js)
import { translate } from "njs-translate";
const result = await translate("Hello, world!", {
from: "en",
to: ["bg", "de", "fr", "ru"],
});
console.log(result);
// {
// bg: "Здравей, свят!",
// de: "Hallo Welt!",
// fr: "Bonjour le monde !",
// ru: "Привет мир!"
// }CommonJS
const { translate } = require("njs-translate");
const result = await translate("Hello, world!", { to: ["bg", "de"] });
console.log(result);Auto-detect source language
import { translate } from "njs-translate";
// No 'from' needed — Google detects it
const result = await translate("Guten Morgen", {
to: ["en", "fr", "es"],
});
// { en: "Good morning", fr: "Bonjour", es: "Buenos días" }API Reference
translate(text, options)
Translate a string into one or more target languages.
async function translate(text: string, options: TranslateOptions): Promise<TranslationMap>Returns a TranslationMap (Record<string, string>) keyed by target language code. If text is blank, all target keys resolve to "".
TranslateOptions
| Property | Type | Default | Description |
|------------|---------------------------|--------------|-------------|
| to | string \| string[] | required | Target language code(s), e.g. "de" or ["en", "de", "fr"] |
| from | string | "auto" | Source language code. "auto" lets Google detect it automatically. |
| delay | number | 150 | Milliseconds to wait between consecutive requests. Increase to reduce rate-limiting. |
| onError | "fallback" \| "throw" | "fallback" | What to do when a single target fails: return source text, or throw TranslationError. |
const result = await translate("Good morning", {
from: "en",
to: ["bg", "de", "ru"],
delay: 200, // 200 ms between requests
onError: "fallback", // default — failed languages return the source text
});translateTo(text, to, from?)
Translate a string into a single target language. Returns a plain string.
async function translateTo(text: string, to: string, from?: string): Promise<string>| Parameter | Type | Default | Description |
|-----------|----------|----------|-------------|
| text | string | | The text to translate. |
| to | string | | Target language code. |
| from | string | "auto" | Source language code. |
import { translateTo } from "njs-translate";
const german = await translateTo("Hello", "de");
// "Hallo"
const english = await translateTo("Добро утро", "en", "bg");
// "Good morning"translateBatch(texts, options)
Translate an array of strings into the same set of target languages.
Returns an array of TranslationMap objects in the same order as the input.
async function translateBatch(texts: string[], options: TranslateOptions): Promise<TranslationMap[]>import { translateBatch } from "njs-translate";
const results = await translateBatch(["Hello", "Goodbye"], {
from: "en",
to: ["bg", "de"],
});
// [
// { bg: "Здравейте", de: "Hallo" },
// { bg: "Довиждане", de: "Auf Wiedersehen" }
// ]TranslationMap
type TranslationMap = Record<string, string>;A plain object whose keys are BCP 47 language codes and values are translated strings.
TranslationError
Thrown when onError: "throw" is set and a translation request fails.
import { translate, TranslationError } from "njs-translate";
try {
const result = await translate("Hello", {
to: ["de", "fr"],
onError: "throw",
});
} catch (err) {
if (err instanceof TranslationError) {
console.log(err.lang); // "de" — the language that failed
console.log(err.sourceText); // "Hello" — original input text
console.log(err.message); // HTTP error description
}
}| Property | Type | Description |
|--------------|----------|-------------|
| lang | string | Target language code that caused the error. |
| sourceText | string | The original source text being translated. |
| message | string | Human-readable error message. |
| name | string | Always "TranslationError". |
Error Handling
Default: silent fallback
By default (onError: "fallback"), if a request fails for a specific language, njs-translate returns the original source text for that key without throwing. All other languages in the same call are unaffected.
const result = await translate("Hello", { to: ["de", "fr"] });
// If "de" fails → result.de === "Hello" (source text)
// If "fr" succeeds → result.fr === "Bonjour"Strict mode: throw on failure
Set onError: "throw" to stop immediately on any failure:
const result = await translate("Hello", {
to: ["de", "fr"],
onError: "throw",
});
// Throws TranslationError if any language failsCLI Usage
Basic usage
njs-translate "Hello, world!" --to bg,de,frOutput:
{"bg":"Здравей, свят!","de":"Hallo Welt!","fr":"Bonjour le monde !"}With explicit source language and pretty-print
njs-translate "Guten Morgen" --from de --to en,fr,ru --prettyOutput:
{
"en": "Good morning",
"fr": "Bonjour",
"ru": "Доброе утро"
}Without global install (npx)
npx njs-translate "Привет" --from ru --to en,bg,de --prettyAll options
Usage: njs-translate <text> [options]
Arguments:
text Text to translate
Options:
--to <langs> Comma-separated target language codes (required)
Example: --to en,de,fr
--from <lang> Source language code, or 'auto' to detect (default: "auto")
--delay <ms> Milliseconds between requests (default: "150")
--pretty Pretty-print the JSON output
-V, --version Output the version number
-h, --help Display help for command
Examples:
$ njs-translate "Hello, world!" --to bg,de,fr
$ njs-translate "Guten Morgen" --from de --to en,fr --pretty
$ njs-translate "Привет" --from ru --to en --delay 0Pipe to jq
Since the output is JSON, you can pipe it to jq for further processing:
njs-translate "Good morning" --to de,fr,es | jq '.de'
# "Guten Morgen"Language Codes
njs-translate uses BCP 47 language codes as supported by Google Translate. A few common ones:
| Code | Language |
|---------|-----------------------|
| en | English |
| de | German |
| fr | French |
| es | Spanish |
| it | Italian |
| pt | Portuguese |
| ru | Russian |
| uk | Ukrainian |
| pl | Polish |
| cs | Czech |
| bg | Bulgarian |
| nl | Dutch |
| tr | Turkish |
| ar | Arabic |
| hi | Hindi |
| ja | Japanese |
| ko | Korean |
| zh-CN | Chinese (Simplified) |
| zh-TW | Chinese (Traditional) |
A complete list of supported language codes is available in Google's documentation.
⚠️ Disclaimer
njs-translate uses Google Translate's unofficial public endpoint — the same one used by the Google Translate browser extension. It does not require an API key.
- This endpoint is not officially supported by Google and may change without notice.
- It may be rate-limited when called too frequently. Use the
delayoption to add pauses between requests (default: 150 ms). - For high-volume, mission-critical production use, consider Google Cloud Translation API with an official API key.
Contributing
Contributions are welcome! Please open an issue or a pull request at github.com/vladi160/njs-translate.
- Fork the repository
- Create a feature branch:
git checkout -b feat/your-feature - Make your changes and add tests
- Run
npm testto ensure everything passes - Submit a pull request
License
MIT © vladi160
