npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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

Readme

njs-translate

npm version license node TypeScript

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 includednjs-translate "Hello" --to bg,de,fr right 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-translate

For global CLI access:

npm install -g njs-translate

Quick 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 fails

CLI Usage

Basic usage

njs-translate "Hello, world!" --to bg,de,fr

Output:

{"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 --pretty

Output:

{
  "en": "Good morning",
  "fr": "Bonjour",
  "ru": "Доброе утро"
}

Without global install (npx)

npx njs-translate "Привет" --from ru --to en,bg,de --pretty

All 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 0

Pipe 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 delay option 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.

  1. Fork the repository
  2. Create a feature branch: git checkout -b feat/your-feature
  3. Make your changes and add tests
  4. Run npm test to ensure everything passes
  5. Submit a pull request

License

MIT © vladi160