Nodejs 调用 Google Translate

Google服务需使用科学上网

npm install google-translate-api --save

修改源码 node_modules/google-translate-api/index.js

使用例子

const fs = require('fs');

const translate = require('google-translate-api');

const tranApi = function (text, iso) {
  return new Promise(function (resolve, reject) {
    translate(text, {to: iso}).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    });
  });
}

const tranTo = async function () {
  let tx = 'I am Chinese'
  console.log(tx)
  let text = await tranApi(tx, 'zh-CN');
  console.log(text.text)

  console.log('')

  let tx1 = '私は中国人です。'
  console.log(tx1)
  let text1 = await tranApi(tx, 'zh-CN');
  console.log(text1.text)

  console.log('')

  let tx2 = '我是法国人。'
  console.log(tx2)
  let text2 = await tranApi(tx, 'fr');
  console.log(text2.text)
}

tranTo()

结果

本文链接地址: Nodejs 调用 Google Translate

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注