專案需將中文程式碼註解/字串翻譯為英文。採用 Node.js 異步 I/O + 事件循環,三階段處理:掃描提取中文 → Google 翻譯 API → 批次替換寫回。
var fs = require('fs'), http = require('http');
var filePath = 'D:\\WORK_new';
var logPath = 'D:\\chinese.log';
var dict = {}; // 中英對照表
// 1. 掃描階段:走訪目錄,正則提取中文字串
new FileWalker().walkDir(filePath, function(data) {
if (!data) return;
var match = data.match(/[\u4e00-\u9fa5]+/g);
if (match) match.forEach(function(ch) { dict[ch] = ''; });
}, function() {
console.log('掃描完成');
saveDict();
});
// 2. 翻譯階段:讀取字典,呼叫 Google 翻譯
function translateDict() {
loadDict(function() {
var pending = 0;
for (var key in dict) if (!dict[key]) {
pending++;
(function(k) {
http.get(encodeURI("https://translate.google.cn/translate_a/t?client=t&hl=zh-CN&sl=zh-CN&tl=en&ie=UTF-8&oe=UTF-8&oc=2&otf=1&ssel=3&tsel=6&sc=2&q=" + k), function(res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function(c){ body += c; });
res.on('end', function(){
try { dict[k] = eval('('+body+')')[0][0][0]; }
catch(e) { dict[k] = ''; }
if (--pending === 0) { saveDict(); console.log('翻譯完成'); }
});
}).on('error', function(){ if(--pending===0){ saveDict(); } });
})(key);
}
});
}
// 3. 替換階段:重新走訪,以字典替換中文
function replaceAll() {
loadDict(function() {
new FileWalker().walkDir(filePath, function(data, fpath) {
fs.writeFile(fpath, data.replace(/[\u4e00-\u9fa5]+/g, function(ch){
return dict[ch] || ch;
}), {encoding:'ascii', flag:'w'}, function(err){ if(err) throw err; });
}, function(){ console.log('替換完成'); });
});
}
function FileWalker() {
var idx = 0;
function readFile(p, fileCb, doneCb) {
fs.readFile(p, {encoding:'utf8'}, function(err, data){
idx--;
if (err) { console.error(err, p); data = ''; }
fileCb(data, p);
if (idx === 0) doneCb();
});
}
function walkDir(p, fileCb, doneCb) {
fs.readdir(p, function(err, files){
files.forEach(function(f){
var full = p + '/' + f;
if (fs.statSync(full).isDirectory()) walkDir(full, fileCb, doneCb);
else if (/\.(js|html|htm|jsp)$/.test(f)) { idx++; readFile(full, fileCb, doneCb); }
});
});
}
this.walkDir = function(p, fileCb, doneCb) { idx = 0; walkDir(p, fileCb, doneCb); };
}
fs.readFile 預設 UTF-8 讀 GBK 會亂碼。解法:以 BOM 偵測、或外部工具統一轉碼。if (用戶 != null) 變成 if (user != null) 以外的誤譯。[\u4e00-\u9fa5]+ 會抓到單一中文標點,需人工清洗字典。