Text Translation Using the DeepL API in Node.js
Build a Command-Line Translator Using the DeepL API in Node.js
In today’s globalized world, language translation is a must-have feature for many applications. Whether you’re building a multilingual website, a chatbot, or simply experimenting with APIs, integrating translation capabilities can significantly enhance the user experience. In this post, we’ll walk you through how to build a command-line translator using the DeepL API in Node.js. This tool will allow users to input text and a target language, returning the translated text instantly.
What is DeepL?
DeepL is a cutting-edge translation service renowned for its high-quality, natural-sounding translations. It supports 29 languages and offers both free and paid API plans, making it accessible for developers of all levels. The DeepL API is easy to integrate and provides fast, accurate translations, making it a great choice for your translation needs.
Why Use DeepL?
High-Quality Translations: DeepL is known for its context-aware, accurate translations that often outperform other services.
Wide Language Support: With support for 29 languages, including English, Spanish, French, German, Chinese, and more, DeepL enables seamless global communication.
Easy Integration: The DeepL API is simple to use, well-documented, and easy to integrate into your applications.
Flexible Pricing: With both free and paid plans, DeepL is accessible to projects of all sizes.
Prerequisites
Before we dive into the code, make sure you have the following:
Node.js installed on your machine. You can download it from nodejs.org.
A DeepL API key. You can get one by signing up on the DeepL API Developer Page.
Basic knowledge of JavaScript and Node.js.
Step 1: Set Up Your Node.js Project
Start by creating a new project directory and navigating into it:
mkdir deepl-cli-translator
cd deepl-cli-translator
Next, initialize your Node.js project:
npm init -y
Install the required dependencies:
npm install deepl-node dotenv
deepl-node
: The official DeepL Node.js library.dotenv
: A package to load environment variables from a.env
file.
Step 2: Store Your API Key Securely
Create a .env
file in your project root directory and add your DeepL API key:
DEEPL_API_KEY=your-api-key-here
Add .env
to your .gitignore
file to avoid committing sensitive information:
echo ".env" >> .gitignore
Step 3: Write the Translation Code
Create a file named translate.js
and add the following code:
require("dotenv").config(); // Load environment variables
const deepl = require("deepl-node");
const readline = require("readline");
// Initialize the DeepL translator
const translator = new deepl.Translator(process.env.DEEPL_API_KEY);
/**
* Translates text to the target language.
* @param {string} text - The text to translate.
* @param {string} targetLanguage - The target language code (e.g., "es" for Spanish).
* @returns {Promise<string>} - The translated text.
*/
async function translateText(text, targetLanguage) {
if (!text || typeof text !== "string") {
throw new Error("Invalid text input. Please provide a valid string.");
}
if (!targetLanguage || typeof targetLanguage !== "string") {
throw new Error("Invalid target language. Please provide a valid language code.");
}
try {
const result = await translator.translateText(text, null, targetLanguage);
return result.text;
} catch (err) {
console.error(`Error translating text: ${err.message}`);
throw err;
}
}
// Set up readline for user input
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
/**
* Prompt the user for input and translate it.
*/
function promptUser() {
rl.question("Enter the text you want to translate (or type 'exit' to quit): ", async (text) => {
if (text.toLowerCase() === "exit") {
console.log("Goodbye!");
rl.close();
return;
}
rl.question("Enter the target language code (e.g., 'es' for Spanish): ", async (targetLanguage) => {
try {
const translatedText = await translateText(text, targetLanguage);
console.log(`Translated text: ${translatedText}`);
} catch (err) {
console.error(`Translation failed: ${err.message}`);
}
// Prompt the user again
promptUser();
});
});
}
// Start the program
console.log("Welcome to the DeepL Translator!");
promptUser();
Step 4: Supported Languages
DeepL supports 29 languages. Below is the list of supported languages and their corresponding language codes:
Language | Language Code |
Bulgarian | bg |
Czech | cs |
Danish | da |
German | de |
Greek | el |
English | en |
Spanish | es |
Estonian | et |
Finnish | fi |
French | fr |
Hungarian | hu |
Indonesian | id |
Italian | it |
Japanese | ja |
Korean | ko |
Lithuanian | lt |
Latvian | lv |
Norwegian (Bokmål) | nb |
Dutch | nl |
Polish | pl |
Portuguese | pt |
Romanian | ro |
Russian | ru |
Slovak | sk |
Slovenian | sl |
Swedish | sv |
Turkish | tr |
Ukrainian | uk |
Chinese (Simplified) | zh |
Step 5: Run the Code
Save the code in a file, e.g., translate.js
.
Ensure your .env
file contains the correct DeepL API key:
DEEPL_API_KEY=your-api-key-here
Run the program:
node translate.js
Example Usage
When you run the program, it will look like this:
Welcome to the DeepL Translator!
Enter the text you want to translate (or type 'exit' to quit): Hello, world!
Enter the target language code (e.g., 'es' for Spanish): es
Translated text: ¡Hola, mundo!
Enter the text you want to translate (or type 'exit' to quit): How are you?
Enter the target language code (e.g., 'es' for Spanish): fr
Translated text: Comment ça va ?
Enter the text you want to translate (or type 'exit' to quit): exit
Goodbye!
Conclusion
This command-line translator is a simple yet powerful tool for translating text into multiple languages using the DeepL API. With support for 29 languages, DeepL makes it easy to build multilingual applications that cater to a global audience. Whether you’re looking to add translation capabilities to your app or just experimenting with the DeepL API, this guide provides everything you need to get started.