node google cloud translation api - DashingDigit001/WikiPage GitHub Wiki
-
建立或是選擇一個 google cloud 專案
-
在 google cloud 選擇該專案,Menu -> APIs & Services -> Enable apis and services -> cloud translation api -> enable
-
建立 Service account , Menu -> IAM & Admin -> Service accounts -> Create Service Account -> 輸入 Service Account Name -> 輸入 Service account description -> 選擇 role Cloud Translation API Admin -> Done
-
Service account -> actions -> Manage keys -> add key -> create key json -> 建立完成後會自動下載 sa key
-
在電腦環境加入 sa key ,For example:
$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"
-
在 node 的專案下
npm install --save @google-cloud/translate
-
專案下建立 index.js
const { TranslationServiceClient } = require('@google-cloud/translate'); const translationClient = new TranslationServiceClient(); const projectId = 'fluent-webbing-366003'; const location = 'global'; const text = 'hello world'; async function translateText() { // Construct request const request = { parent: `projects/${projectId}/locations/${location}`, contents: [text], mimeType: 'text/plain', // mime types: text/plain, text/html sourceLanguageCode: 'en', targetLanguageCode: 'zh-tw', }; // Run request const [response] = await translationClient.translateText(request); for (const translation of response.translations) { console.log(`Translation: ${translation.translatedText}`); } } translateText();
-
執行程式
node index