1.首先安装一下翻译依赖,这里采用的是谷歌翻译
npm install --save google-translate-api
安装成功后将node_module中google-translate-api和google-translate-token这两个文件夹的index.js,里面的
https://translate.google.com全部替换为 https://translate.google.cn
然后在google-translate-api 的index.js中的第三十五行中 t 改为gtx
client: 'gtx',//client: 't',=>client: 'gtx',
实现代码如下:
var fs = require('fs');
var join = require('path').join;
var translate = require('google-translate-api');
var conf = require('./config.js');//獲取配置信息
var arr = [];
var fileItem = [];
var num = 0;//计数器
function getJsonFiles(jsonPath){
let jsonFiles = [];
var i = 0;
function findJsonFile(path){
let files = fs.readdirSync(path);
for(let n = 0;n<files.length;n++){
let fPath = join(path,files[n]);
let stat = fs.statSync(fPath);
let tempPath = fPath.substring(fPath.lastIndexOf("\\")+1,fPath.length);
if(stat.isDirectory() === true &&(conf.cf.skipFolderName.indexOf(tempPath)==-1&&conf.cf.skipPath.indexOf(fPath)==-1) ) {//
findJsonFile(fPath);
}
if (stat.isFile() === true) {
jsonFiles.push(...fPath);
readFileKeyword(fPath,m=>{
fileItem.push(...m);
});
i++;
}
}
}
findJsonFile(jsonPath);
let initData = deletRrepetitionItemAndFormat(fileItem);
//翻譯
conf.cf.languages.forEach(el=>{
if(el=="en-US"){
writeTranlateData(el+".json",initData,"en",conf.cf.Mode);
}else{
writeTranlateData(el+".json",initData,el,conf.cf.Mode);
}
})
}
getJsonFiles(conf.cf.sourceCodePath);//執行入口
/**
* 判斷文件是否存在
* @param {string} path -文件路勁
* @return {bool} -true存在 false不存在
*/
function fsExistsSync(path){
try{
fs.accessSync(path)
}catch(e){
console.log(e);
return false;
}
return true;
}
/**
* 读取文件中的指定数据
* @param {string} path - 傳入文件夾地址相對路徑
* @param {function} fn -回調函數
*/
function readFileKeyword(path,fn){
let str = fs.readFileSync(path,'utf-8');
let temp = [];
for(let n in conf.cf.patterns){
let m = str.match(conf.cf.patterns[n]);
if(m){
temp.push(...m);
}
}
if(temp.length)
fn(temp);
}
/**
* 數據去重並格式化數據
* @param {Array} arr- 需要去重的數組
* @return {Array} -返回已去重的數組
*/
function deletRrepetitionItemAndFormat(arr){
var Arr = new Set(arr);
let temp = [];
Array.from(Arr).forEach(el=>{
num++;//计数器自增
temp.push({
text:el,
orderBy:num,
translate:""
})
})
return temp;
}
/**
* 寫入文件
* @param {String} path - 寫入文件的路徑
* @param {String} str -寫入文件的數據
*/
function writeFile(path,str){
// fs.appendFileSync(path,str);
fs.writeFileSync(path,str);
}
/**
* 多語言翻譯
* @param {String} data -需要翻譯的數據
* @param {String} language -需要翻譯成的語言 如 en 、 zh-TW 、 zh-CN
* @param {function} callback - 翻譯後的回調函數
*/
function Translate(data,language,callback){
translate(data,{to:language}).then(res=>{
callback(res);
}).catch(err=>{
callback(err);
console.log(err);
})
}
/**
* 排序
*/
function compare(propertyName){
return function(obj1,obj2){
var value1 = obj1[propertyName];
var value2 = obj2[propertyName];
return value1-value2
}
}
/**
* 讀取文件
* @param {String} path -讀取文件
*
*/
function readFile(path){
return fs.readFileSync(path,'utf-8');
}
/**
*
* @param {String} path - 寫入文件地址
* @param {Array} initData -寫入文件的數據
* @param {String} language -需要寫入的語言
* @param {String} ModeStat-寫入語言的狀態
*/
function writeTranlateData(path,initData,language,ModeStat){
let temp = [];
initData.map(item=>{
Translate(item.text,language,res=>{
// console.log(item);
if(conf.cf.skipEnglishKey&&res.from.language.iso=="en"){
temp.push({
text:item.text,
orderBy:item.orderBy,
translate:item.text
});
}else{
temp.push({
text:item.text,
orderBy:item.orderBy,
translate:res.text.replace(/(^\s*)|(\s*$)/g,"")
});
}
if(temp.length==initData.length){
let str = "{\n";
temp.sort(compare("orderBy")).forEach((el,index)=>{
str += ' "'+el.text+'": "'+el.translate+'",\n';
})
str=str.substring(0,str.length-2);
str+="\n}";
if(ModeStat=="Append"){//狀態為追加
if(fsExistsSync(path)){
let readData = fs.readFileSync(path,'utf-8');
readData = JSON.parse(readData);
let strJson = JSON.parse(str);
for(let i in readData){
delete strJson[i];
}
for(let n in strJson){
readData[n]=strJson[n]
}
let writeStr = "{\n";
for(let i in readData){
writeStr += ' "'+i+'": "'+readData[i]+'",\n';
}
writeStr=writeStr.substring(0,writeStr.length-2);
writeStr+="\n}";
writeFile(path,writeStr);
}
}
if(ModeStat=="Create"){//狀態為創建
writeFile(path,str);
}
return;
}
})
})
}
配置文件如下:
var cf = {
sourceCodePath:"D:\\Collection2018\\Insurance\\cms",//源代碼路徑\\pages
skipEnglishKey:true,//當key為全英文時,是否跳過翻譯
languages:['en-US','zh-CN','zh-TW'],//需要翻譯的語言
patterns:{
0:/(?<=\$t(\s*)\((\s*)(\"|\'))[^\'|\"]+/g
},
skipPath:[//需要跳過的路徑(完整路徑,不區分大小寫)
//"d:\\...\\node_module"
"D:\\test\\TestServer\\CMS\\pages\\adminUser"
],
skipFolderName:[//需要跳過的文件夾(文件夾名稱,不區分大小寫)//"plugins",".nuxt","locales","node_modules"
".nuxt","node_modules","locales","plugins"
],
//Mode: Create/Append
Mode:"Create"
}
exports.cf = cf;