Skip to content

Instantly share code, notes, and snippets.

@HereOrCode
Created January 31, 2023 09:30
Show Gist options
  • Save HereOrCode/4742d10b9bf8bfcf248cc44e8ced16c6 to your computer and use it in GitHub Desktop.
Save HereOrCode/4742d10b9bf8bfcf248cc44e8ced16c6 to your computer and use it in GitHub Desktop.
translate file
const arguments = process.argv.slice(2);
const [filePath] = arguments;
main(filePath);
function main(filePath) {
const path = require('path');
const { root, dir, name, ext } = path.parse(filePath);
const fs = require('fs');
const fetch = require('node-fetch');
let oldFileName = `${dir}/${name}${ext}`;
let tempFileName = `${dir}${name}-temp${ext}`
if (root === "" && (dir === "" || dir === ".")) {
oldFileName = `./${name}${ext}`;
tempFileName = `./${name}-temp${ext}`
}
const readerStream = fs.createReadStream(oldFileName);
readerStream.setEncoding('UTF8');
const writerStream = fs.createWriteStream(tempFileName);
let data = '';
// 处理流
readerStream.on('data', async (chunk) => {
var reg = /[\u4e00-\u9fa5]/g;
let index = 0;
let termList = [];
let term = '';
data = chunk;
while (list = reg.exec(chunk)) {
if ((list.index !== index + 1) && term) {
termList.push(term);
term = '';
}
term += list[0];
index = list.index;
}
termList.push(term);
const result = await translateData(termList, data);
writerStream.write(result, 'UTF8');
writerStream.end()
fs.unlink(oldFileName, (error) => {
if (error) {
console.log("delete fille error: ", error);
return;
}
fs.rename(tempFileName, oldFileName, (error) => {
if (error) {
console.log("rename fille error: ", error);
return;
};
console.log(`${oldFileName} translate finish`);
});
})
});
readerStream.on('end', () => {
});
readerStream.on('error', (err) => {
console.log("readerStream: ", err.stack);
});
const translateData = (termList, data) => {
return new Promise(async (resolve, _) => {
const dict = {}
if (termList && termList.length) {
for (const item of termList) {
const [{ translation }] = await translateText(item);
dict[item] = translation;
data = data.replace(item, translation)
}
resolve(data);
}
});
}
const translateText = (
content,
language = "en"
) => {
const config = {
text: content,
source_language: "detect",
target_language: language,
};
return new Promise((resolve, _) => {
fetch("https://translate.volcengine.com/crx/translate/v1/", {
headers: {
accept: "application/json, text/plain, */*",
"content-type": "application/json",
},
body: JSON.stringify(config),
method: "POST",
mode: "cors",
credentials: "include",
})
.then((data) => data.json())
.then((data) => resolve([data, null]))
.catch(() => {
resolve([null, error_text]);
});
});
};
}
{
"name": "translate-file",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"node-fetch": "1.7.3"
}
}
# node index.js your project path/your project file
node index.js /Users/Mike/Desktop/TestProject/js/background.js    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment