Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Official Node.js library for the DeepL language translation API.

License

NotificationsYou must be signed in to change notification settings

DeepLcom/deepl-node

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

205 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

VersionMinimum node.js versionLicense: MIT

Official Node.js Client Library for the DeepL API.

TheDeepL API is a language translation API that allows othercomputer programs to send texts and documents to DeepL's servers and receivehigh-quality translations. This opens a whole universe of opportunities fordevelopers: any translation product you can imagine can now be built on top ofDeepL's best-in-class translation technology.

The DeepL Node.js library offers a convenient way for applications written forNode.js to interact with the DeepL API. We intend to support all API functionswith the library, though support for new features may be added to the libraryafter they're added to the API.

Getting an authentication key

To use the package, you'll need an API authentication key. To get a key,please create an account here. With a DeepL API Free accountyou can translate up to 500,000 characters/month for free.

Installation

npm install deepl-node

Requirements

The package officially supports Node.js version 12, 14, 16, 17, 18, 20, 22 and 24.

We strongly recommend upgrading to a supported Node.js version as we will be dropping support for end-of-life versions in 2025. You can find the Node versions and support timelineshere.

Usage

Import the package and construct aDeepLClient. The first argument is a stringcontaining your API authentication key as found in yourDeepL Pro Account.

Be careful not to expose your key, for example when sharing source code.

An example usingasync/await and ES Modules:

import*asdeeplfrom'deepl-node';constauthKey="f63c02c5-f056-...";// Replace with your keyconstdeeplClient=newdeepl.DeepLClient(authKey);(async()=>{constresult=awaitdeeplClient.translateText('Hello, world!',null,'fr');console.log(result.text);// Bonjour, le monde !})();

This example is for demonstration purposes only. In production code, theauthentication key should not be hard-coded, but instead fetched from aconfiguration file or environment variable.

If you are using CommonJS, you should instead require the package:

constdeepl=require('deepl-node');constdeeplClient=newdeepl.DeepLClient(authKey);

DeepLClient accepts options as the second argument, seeConfiguration for more information.

AllDeepLClient functions return promises, and for brevity the examples in thisfile useawait andtry/catch blocks, however Promise-chaining is alsopossible:

deeplClient.translateText('Hello, world!',null,'fr').then((result)=>{console.log(result.text);// Bonjour, le monde !}).catch((error)=>{console.error(error);});

The package also supports TypeScript:

import*asdeeplfrom'deepl-node';(async()=>{consttargetLang:deepl.TargetLanguageCode='fr';constresults=awaitdeeplClient.translateText(['Hello, world!','How are you?'],null,targetLang,);results.map((result:deepl.TextResult)=>{console.log(result.text);// Bonjour, le monde !});})();

Translating text

To translate text, calltranslateText(). The first argument is a stringcontaining the text you want to translate, or an array of strings if you want totranslate multiple texts.

The second and third arguments are the source and target language codes.Language codes arecase-insensitive strings according to ISO 639-1, forexample'de','fr','ja''. Some target languages also include the regionalvariant according to ISO 3166-1, for example'en-US', or'pt-BR'. The sourcelanguage also acceptsnull, to enable auto-detection of the source language.

The last argument totranslateText() is optional, and specifies extratranslation options, seeText translation optionsbelow.

translateText() returns a Promise that fulfills with aTextResult, or anarray ofTextResults corresponding to your input text(s).TextResult has thefollowing properties:

  • text is the translated text,
  • detectedSourceLang is the detected source language code,
  • billedCharacters is the number of characters billed for the text.
  • modelTypeUsed indicates the translation model used, but isundefinedunless themodelType option is specified.
// Translate text into a target language, in this case, French:consttranslationResult=awaitdeeplClient.translateText('Hello, world!','en','fr');console.log(translationResult.text);// 'Bonjour, le monde !'// Translate multiple texts into British English:consttranslations=awaitdeeplClient.translateText(['お元気ですか?','¿Cómo estás?'],null,'en-GB',);console.log(translations[0].text);// 'How are you?'console.log(translations[0].detectedSourceLang);// 'ja'console.log(translations[0].billedCharacters);// 7 - the number of characters in the source text "お元気ですか?"console.log(translations[1].text);// 'How are you?'console.log(translations[1].detectedSourceLang);// 'es'console.log(translations[1].billedCharacters);// 12 - the number of characters in the source text "¿Cómo estás?"// Translate into German with less and more Formality:console.log(awaitdeeplClient.translateText('How are you?',null,'de',{formality:'less'}));// 'Wie geht es dir?'console.log(awaitdeeplClient.translateText('How are you?',null,'de',{formality:'more'}));// 'Wie geht es Ihnen?'

Text translation options

  • splitSentences: specify how input text should be split into sentences,default:'on'.
    • 'on': input text will be split into sentences using both newlines andpunctuation.
    • 'off': input text will not be split into sentences. Use this forapplications where each input text contains only one sentence.
    • 'nonewlines': input text will be split into sentences using punctuationbut not newlines.
  • preserveFormatting: controls automatic-formatting-correction. Set totrueto prevent automatic-correction of formatting, default:false.
  • formality: controls whether translations should lean toward informal orformal language. This option is only available for some target languages, seeListing available languages. Use theprefer_* options to apply formality if it is available for the target
    language, or otherwise fallback to the default.
    • 'less': use informal language.
    • 'more': use formal, more polite language.
    • 'default': use default formality.
    • 'prefer_less': use informal language if available, otherwise default.
    • 'prefer_more': use formal, more polite language if available, otherwise default.
  • glossary: specifies a glossary to use with translation, either as a stringcontaining the glossary ID, or aMultilingualGlossaryInfo/GlossaryInfo as returned bygetMultilingualGlossary()/getGlossary().
  • styleRule: specifies a style rule to use with translation, either as a stringcontaining the style rule ID, or aStyleRuleInfo as returned bygetAllStyleRules().
  • context: specifies additional context to influence translations, that is nottranslated itself. Characters in thecontext parameter are not counted toward billing.See theAPI documentation for more information andexample usage.
  • customInstructions: an array of instructions to customize the translation behavior.Up to 10 custom instructions can be specified, each with a maximum of 300 characters.Important: The target language must bede,en,es,fr,it,ja,ko,zhor any variants of these languages.Note: Any request with thecustomInstructions parameter enabled will usethequality_optimized model type as the default. Requests combiningcustomInstructions andmodelType: latency_optimized will be rejected.
  • modelType: specifies the type of translation model to use, options are:
    • 'quality_optimized': use a translation model that maximizes translationquality, at the cost of response time. This option may be unavailable forsome language pairs.
    • 'prefer_quality_optimized': use the highest-quality translation modelfor the given language pair.
    • 'latency_optimized': use a translation model that minimizes responsetime, at the cost of translation quality.
  • tagHandling: type of tags to parse before translation, options are'html'and'xml'.
  • tagHandlingVersion: specifies which version of the tag handling algorithm to use.Options arev1 andv2.

The following options are only used iftagHandling is'xml':

  • outlineDetection: specifyfalse to disable automatic tag detection,default istrue.
  • splittingTags: list of XML tags that should be used to split text intosentences. Tags may be specified as an array of strings (['tag1', 'tag2']),or a comma-separated list of strings ('tag1,tag2'). The default is an emptylist.
  • nonSplittingTags: list of XML tags that should not be used to split textinto sentences. Format and default are the same as forsplittingTags.
  • ignoreTags: list of XML tags that containing content that should not betranslated. Format and default are the same as forsplittingTags.
  • extraRequestParameters: Extra body parameters to be passed along with theHTTP request. Only string values are permitted.For example:{'param': 'value', 'param2': 'value2'}Note: Extra request parameters can override parameters explicitly set by the library(such astarget_lang,source_lang, etc.). This is primarily useful for testing oraccessing beta features.

Translating documents

To translate documents, calltranslateDocument(). The first and secondarguments are the input and output files. These arguments accept stringscontaining file paths, or Streams or FileHandles opened for reading/writing. Theinput file may also be given as a Buffer containing the file data. Note that ifthe input file is not given as a file path, then thefilename option isrequired.

The third and fourth arguments are the source and target language codes, andthey work exactly the same as when translating text withtranslateText().

The last argument totranslateDocument() is optional, and specifies extratranslation options, seeDocument translation options below.

// Translate a formal document from English to German:try{awaitdeeplClient.translateDocument('Instruction Manual.docx','Bedienungsanleitung.docx','en','de',{formality:'more'},);}catch(error){// If the error occurs after the document was already uploaded,// documentHandle will contain the document ID and keyif(error.documentHandle){consthandle=error.documentHandle;console.log(`Document ID:${handle.documentId}, `+`Document key:${handle.documentKey}`);}else{console.log(`Error occurred during document upload:${error}`);}}

translateDocument() wraps multiple API calls: uploading, polling status untilthe translation is complete, and downloading. If your application needs toexecute these steps individually, you can instead use the following functionsdirectly:

  • uploadDocument(),
  • getDocumentStatus() (orisDocumentTranslationComplete()), and
  • downloadDocument()

Document translation options

  • formality: same as inText translation options.
  • glossary: same as inText translation options.
  • styleRule: same as inText translation options.
  • filename: if the input file is not provided as file path, this option isneeded to specify the file extension.
  • extraRequestParameters: same as inText translation options.
  • enableDocumentMinification: Abool value. If set totrue, the library will try to minify a documentbefore translating it through the API, sending a smaller document if the file contains a lot of media. This iscurrently only supported forpptx anddocx files. See alsoDocument minification.

Document minification

In some contexts, one can end up with large document files (e.g. PowerPoint presentationsor Word files with many contributors, especially in a larger organization). However, theDeepL API enforces a limit of 30 MB for most of these files (see Usage Limits in the docs).In the case that most of this size comes from media included in the documents (e.g. images,videos, animations), document minification can help.In this case, the library will create a temporary directory to extract the document into,replace the large media with tiny placeholders, create a minified document, translate thatvia the API, and re-insert the original media into the original file. Please note that thisrequires a bit of additional (temporary) disk space, we recommend at least 2x the file sizeof the document to be translated.

To use document minification, simply pass the option to thetranslateDocument() function:

awaitdeeplClient.translateDocument(inFile,outFile,"en","de",{enableDocumentMinification:true});

In order to use document minification with the lower-leveluploadDocument(),isDocumentTranslationComplete() anddownloadDocument() methods as well as other details,see theDocumentMinifier class.

Currently supported document types for minification:

  1. pptx
  2. docx

Currently supported media types for minification:

  1. png
  2. jpg
  3. jpeg
  4. emf
  5. bmp
  6. tiff
  7. wdp
  8. svg
  9. gif
  10. mp4
  11. asf
  12. avi
  13. m4v
  14. mpg
  15. mpeg
  16. wmv
  17. mov
  18. aiff
  19. au
  20. mid
  21. midi
  22. mp3
  23. m4a
  24. wav
  25. wma

Glossaries

Glossaries allow you to customize your translations using defined terms.Multiple glossaries can be stored with your account, each with a user-specifiedname and a uniquely-assigned ID.

v2 versus v3 glossary APIs

The newest version of the glossary APIs are the/v3 endpoints, allowing bothediting functionality plus support for multilingual glossaries. New methods andobjects have been created to support interacting with these new glossaries.Due to this new functionality, users are recommended to utilize thesemultilingual glossary methods. However, to continue using thev2 glossary APIendpoints, please continue to use the existing endpoints in thetranslator.ts(e.g.createGlossary(),getGlossary(), etc).

To migrate to use the new multilingual glossary methods from the currentmonolingual glossary methods, please refer tothis migration guide.

The following sections describe how to interact with multilingual glossariesusing the new functionality:

You can create a multi-lingual glossary with your desired terms and name usingcreateMultilingualGlossary(). Glossaries created via the /v3 endpoints can nowsupport multiple source-target language pairs. Note: Glossaries are onlysupported for some language pairs, check theDeepL API documentation for more information.

// Create a glossary with an English to German dictionary containing two terms:constentries=newdeepl.GlossaryEntries({entries:{artist:'Maler',prize:'Gewinn'}});constglossaryEnToDe=awaitdeeplClient.createMultilingualGlossary('My glossary',[{sourceLangCode:'en',targetLangCode:'de',entries:entries}]);

You can also upload a glossary downloaded from the DeepL website usingcreateGlossaryWithCsv(). Instead of supplying the entries as a dictionary,provide the CSV content as a string.

constfs=require('fs').promises;constfilePath='/path/to/glossary_file.csv';letcsvContent='';try{csvContent=awaitfs.readFile(filePath,'utf-8');}catch(error){console.error(`Error reading file at${filePath}:`,error);throwerror;}constcsvContent=awaitreadCsvFile(filePath);constglossaryEnToDe=awaitdeeplClient.createMultilingualGlossaryWithCsv('My glossary','en','de',csvContent);

TheAPI documentation explains the expected CSV format indetail.

Functions to get, list, and delete stored glossaries are also provided.

// Find details about the glossary named 'My glossary'constglossaries=awaitdeeplClient.listMultilingualGlossaries();constglossary=glossaries.find((glossary)=>glossary.name=='My glossary');console.log(`Glossary ID:${glossary.glossaryId}`);for(constglossaryDictofglossary.dictionaries){console.log(`Contains dictionary, source:${glossaryDict.sourceLang}, target:${glossaryDict.targetLang}, with${glossaryDict.entryCount} entries.`;)}

To use a glossary when translating text and documents, include the ID(orMultilingualGlossaryInfo object returned bylistMultilingualGlossaries() orcreateMultilingualGlossary()) inthe function call. The source and target languages must match the glossary.

constresultWithGlossary=awaitdeeplClient.translateText('The artist was awarded a prize.','en','de',{ glossary},);console.log(resultWithGlossary.text);// 'Der Maler wurde mit einem Gewinn ausgezeichnet.'// Without using a glossary would give:  'Der Künstler wurde mit einem Preis ausgezeichnet.'

Getting, listing, and deleting stored glossaries

Functions to get, list, and delete stored glossaries are also provided:

  • getMultilingualGlossary() takes a glossary ID and returns aPromise<MultilingualGlossaryInfo> object for a stored glossary, or raises anexception if no such glossary is found.
  • listMultilingualGlossaries() returns a promise of a list ofMultilingualGlossaryInfo objectscorresponding to all of your stored glossaries.
  • deleteMultilingualGlossary() takes a glossary ID orMultilingualGlossaryInfoobject and deletes the stored glossary from the server, or raises anexception if no such glossary is found.
  • deleteMultilingualGlossaryDictionary() takes a glossary ID orGlossaryInfo object toidentify the glossary. Additionally takes in a source and target language or aMultilingualGlossaryDictionaryInfo object and deletes the stored dictionaryfrom the server, or raises an exception if no such glossary dictionary is found.
constglossaryDicts=[{sourceLangCode:'en',targetLangCode:'de',entries:newdeepl.GlossaryEntries({entries:{'hello':'hallo'}})},{sourceLangCode:'de',targetLangCode:'en',entries:newdeepl.GlossaryEntries({entries:{'hallo':'hello'}})}];constcreatedGlossary=awaitdeeplClient.createMultilingualGlossary('My Glossary',glossaryDicts);constglossaries=awaitdeeplClient.listMultilingualGlossaries();// Delete a dictionary in a glossaryawaitdeeplClient.deleteMultilingualGlossaryDictionary(createdGlossary,'de','en');// Delete a glossary by namefor(constglossaryofglossaries){if(glossary.name==="Old glossary"){awaitdeeplClient.deleteMultilingualGlossary(glossary);}}

Listing entries in a stored glossary

TheMultilingualGlossaryInfo object does not contain the glossary entries, butinstead only the number of entries in theentryCount property.

To list the entries contained within a stored glossary, usegetMultilingualGlossaryEntries() providing either theMultilingualGlossaryInfo object or glossaryID and the source and target language pair:

constentriesObj=awaitdeeplClient.getMultilingualGlossaryDictionaryEntries(createdGlossary,'en','de');console.log(entriesObj.entries.toTsv());// 'hello\thallo'

Editing a glossary

Functions to edit stored glossaries are also provided:

  • updateMultilingualGlossaryDictionary() takes a glossary ID orMultilingualGlossaryInfoobject, plus a source language, target language, and a dictionary of entries.It will then either update the list of entries for that dictionary (eitherinserting new entries or replacing the target phrase for any existingentries) or will insert a new glossary dictionary if that language pair isnot currently in the stored glossary.
  • replaceMultilingualGlossaryDictionary() takes a glossary ID orMultilingualGlossaryInfoobject, plus a source language, target language, and a dictionary of entries.It will then either set the entries to the parameter value, completelyreplacing any pre-existing entries for that language pair.
  • updateMultilingualGlossaryName() takes a glossary ID orMultilingualGlossaryInfoobject, plus the new name of the glossary.
constglossaryDicts=[{sourceLangCode:'en',targetLangCode:'de',entries:newdeepl.GlossaryEntries({entries:{"artist":"Maler","hello":"guten tag"}})}];constmyGlossary=awaitdeeplClient.createMultilingualGlossary('My Glossary',glossaryDicts);constnewDict={sourceLangCode:'en',targetLangCode:'de',entries:newdeepl.GlossaryEntries({entries:{"hello":"hallo","prize":"Gewinn"}})};constupdatedGlossary=awaitdeeplClient.updateMultilingualGlossaryDictionary(myGlossary,newDict);constentriesObj=awaitdeeplClient.getMultilingualGlossaryDictionaryEntries(createdGlossary,'en','de');console.log(entriesObj.entries.toTsv());// {'artist': 'Maler', 'hello': 'hallo', 'prize': 'Gewinn'}

For examples for the other methods please seethis migration guide

Style Rules

Style rules allow you to customize your translations using a managed, shared listof rules for style, formatting, and more. Multiple style rules can be stored withyour account, each with a user-specified name and a uniquely-assigned ID.

Creating and managing style rules

Currently style rules must be created and managed in the DeepL UI viahttps://www.deepl.com/en/custom-rules. Full CRUD functionality via the APIs willcome shortly.

Listing all style rules

getAllStyleRules() returns a list ofStyleRuleInfo objectscorresponding to all of your stored style rules. The method accepts optionalparameters:page (page number for pagination, 0-indexed),pageSize (numberof items per page), anddetailed (whether to include detailed configurationrules in theconfiguredRules property).

// Get all style rulesconststyleRules=awaitdeeplClient.getAllStyleRules();for(construleofstyleRules){console.log(`${rule.name} (${rule.styleId})`);}// Get style rules with detailed configurationconststyleRules=awaitdeeplClient.getAllStyleRules({detailed:true});for(construleofstyleRules){if(rule.configuredRules){console.log(`  Number formatting:${rule.configuredRules.numbers}`);}}

Checking account usage

To check account usage, use thegetUsage() function.

The returnedUsage object contains up to three usage subtypes, depending onyour account type:character,document andteamDocument. For API accountscharacter will be defined, the othersundefined.

Each usage subtypes (if defined) havecount andlimit properties giving theamount used and maximum amount respectively, and thelimitReached() functionthat checks if the usage has reached the limit. The top levelUsage object hastheanyLimitReached() function to check all usage subtypes.

constusage=awaitdeeplClient.getUsage();if(usage.anyLimitReached()){console.log('Translation limit exceeded.');}if(usage.character){console.log(`Characters:${usage.character.count} of${usage.character.limit}`);}if(usage.document){console.log(`Documents:${usage.document.count} of${usage.document.limit}`);}

Listing available languages

You can request the list of languages supported by DeepL Translator for text anddocuments using thegetSourceLanguages() andgetTargetLanguages() functions.They both return an array ofLanguage objects.

Thename property gives the name of the language in English, and thecodeproperty gives the language code. ThesupportsFormality property only appearsfor target languages, and is aBoolean indicating whether the target languagesupports the optionalformality parameter.

constsourceLanguages=awaitdeeplClient.getSourceLanguages();for(leti=0;i<sourceLanguages.length;i++){constlang=sourceLanguages[i];console.log(`${lang.name} (${lang.code})`);// Example: 'English (en)'}consttargetLanguages=awaitdeeplClient.getTargetLanguages();for(leti=0;i<targetLanguages.length;i++){constlang=targetLanguages[i];if(lang.supportsFormality){console.log(`${lang.name} (${lang.code}) supports formality`);// Example: 'German (DE) supports formality'}}

Glossaries are supported for a subset of language pairs. To retrieve thoselanguages use thegetGlossaryLanguagePairs() function, which returns an arrayofGlossaryLanguagePair objects. Each hassourceLang andtargetLangproperties indicating that that pair of language codes is supported forglossaries.

constglossaryLanguages=awaitdeeplClient.getGlossaryLanguagePairs();for(leti=0;i<glossaryLanguages.length;i++){constlanguagePair=glossaryLanguages[i];console.log(`${languagePair.sourceLang} to${languagePair.targetLang}`);// Example: 'en to de', 'de to en', etc.}

Writing a Plugin

If you use this library in an application, please identify the application withtheappInfo field in theDeepLClientOptions, which takes the name and version of the app:

constoptions={appInfo:{appName:'sampleNodeTranslationApp',appVersion:'1.2.3'},};constdeepl=newdeepl.DeepLClient('YOUR_AUTH_KEY',options);

This information is passed along when the library makes calls to the DeepL API.Both name and version are required.

Configuration

TheDeepLClient constructor accepts configuration options as a second argument,for example:

constoptions={maxRetries:5,minTimeout:10000};constdeepl=newdeepl.DeepLClient('YOUR_AUTH_KEY',options);

The available options are:

  • maxRetries: the maximumNumber of failed HTTP requests to retry, perfunction call. By default, 5 retries are made. SeeRequest retries.
  • minTimeout: theNumber of milliseconds used as connection timeout for eachHTTP request retry. The default value is 10000 (10 seconds).
  • serverUrl:string containing the URL of the DeepL API, can be overriddenfor example for testing purposes. By default, the URL is selected based on theuser account type (free or paid).
  • headers: extra HTTP headers attached to every HTTP request. By default, noextra headers are used. Note that Authorization and User-Agent headers areadded automatically but may be overridden by this option.
  • proxy: define the hostname, and port of the proxy server, and optionallythe protocol, and authorization (as an auth object with username andpassword fields).

Rephrasing Text

To rephrase text, callrephraseText(). The first argument is a string containing the text you want to rephrase, or an array of strings if you want to rephrase multiple texts.

The second argument is the target language code. Language codes arecase-insensitive strings, for example,'de','fr','en'. The target language code can also benull to enable auto-detection of the target language.

The last two arguments,writingStyle andtone, are optional and specify the writing style and tone of the rephrased text. Possible values are defined in theWritingStyle andWritingTone enums.

rephraseText() returns a Promise that fulfills with anImprovement object or an array ofImprovement objects corresponding to your input text(s). TheImprovement object has the following properties:

  • text: the rephrased text,
  • detectedSourceLang: the detected source language code,
  • targetLanguage: the target language code.
// Rephrasing a text in academic style:constrephrasedResult=awaitdeepLClient.rephraseText('This is an example text.','en',WritingStyle.ACADEMIC);console.log(rephrasedResult.text);// The rephrased text in academic style// Rephrasing multiple texts in a friendly tone:constrephrasedTexts=awaitdeepLClient.rephraseText(['How are you?','What are you doing today?'],'de',null,WritingTone.FRIENDLY,);console.log(rephrasedTexts[0].text);// The rephrased text for "How are you?" in a friendly toneconsole.log(rephrasedTexts[1].text);// The rephrased text for "What are you doing today?" in a friendly tone

Logging

deepl-node logs debug and info messages for every HTTP request and responseusing theloglevel module, to the'deepl' logger. You can reconfigure thelog level as follows:

importlogfrom'loglevel';log.getLogger('deepl').setLevel('debug');// Or 'info'

Theloglevel package also supports plugins, seethe documentation.

Proxy configuration

You can configure a proxy by specifying theproxy argument when constructing adeepl.DeepLClient:

constoptions={proxy:{host:'localhost',port:3000}};constdeepl=newdeepl.DeepLClient('YOUR_AUTH_KEY',options);

The proxy argument is passed to the underlyingaxios request, see thedocumentation for axios.

Anonymous platform information

By default, we send some basic information about the platform the client libraryis running on with each request, seehere for an explanation.This data is completely anonymous and only used to improve our product, not trackany individual users. If you do not wish to send this data, you can opt-out whencreating yourDeepLClient object by setting thesendPlatformInfo flag intheDeepLClientOptions tofalse like so:

constoptions={sendPlatformInfo:false};constdeepl=newdeepl.DeepLClient('YOUR_AUTH_KEY',options);

Request retries

Requests to the DeepL API that fail due to transient conditions (for example,network timeouts or high server-load) will be retried. The maximum number ofretries can be configured when constructing theDeepLClient object using themaxRetries option. The timeout for each request attempt may be controlledusing theminTimeout option. An exponential-backoff strategy is used, sorequests that fail multiple times will incur delays.

Issues

If you experience problems using the library, or would like to request a newfeature, please open anissue.

Development

We welcome Pull Requests, please read thecontributing guidelines.

Environment Variables

There are multiple ways to manage your own environment variables. You can choose what works best for you. Make sure that only the values for one stage (local, prod, etc) are active at one time.

Using a global .rc file (such as ~/.bashrc):

# Localexport DEEPL_MOCK_SERVER_PORT=3000export DEEPL_AUTH_KEY=ANY_VALUEexport DEEPL_SERVER_URL=http://localhost:3000
# Prod# (Make sure to run `unset DEEPL_MOCK_SERVER_PORT` if it was previously assigned a value)export DEEPL_AUTH_KEY={YOUR_API_KEY}export DEEPL_SERVER_URL=https://api.deepl.com

Using .env file:

(Benefits include: No need to refresh terminal when changing stages, no need to callunset to clear vars, can be used to isolate vars between multiple projects)

  • Copy.env.example file to a.env file
    • The.env file will never be stored in git, so your local credentials will not be shared
  • Edit.env file to your own desired variables
    • If using local mock server, then point to local ports

Tests

Execute the tests usingnpm test. The tests communicate with the DeepL APIusing the authentication key defined by theDEEPL_AUTH_KEY environmentvariable.

Be aware that the tests make DeepL API requests that contribute toward your APIusage.

The test suite may instead be configured to communicate with the mock-serverprovided bydeepl-mock. Although most test cases work for either,some test cases work only with the DeepL API or the mock-server and will beotherwise skipped. The test cases that require the mock-server trigger servererrors and test the client error-handling. To execute the tests usingdeepl-mock, run it in another terminal while executing the tests. Execute thetests usingnpm test with theDEEPL_MOCK_SERVER_PORT andDEEPL_SERVER_URLenvironment variables defined referring to the mock-server.


[8]ページ先頭

©2009-2026 Movatter.jp