fix: improve scripts and js

This commit is contained in:
Nuno Coração
2025-06-20 23:24:40 +01:00
parent 1f49f8f89f
commit 8c42d127ff
7 changed files with 228 additions and 207 deletions

View File

@@ -1,4 +1,4 @@
const fs = require("fs");
const fs = require("fs/promises");
const translate = require("@iamtraction/google-translate");
const defaultLang = "en";
@@ -8,11 +8,8 @@ const targetLangIso = targetLang == "pt" ? "pt-pt" : targetLang;
const targetFilePath = filePath.replace(".md", "." + targetLangIso + ".md");
async function convert(text, from, to) {
var options = {
from: from,
to: to,
};
var translated_text = await translate(text, options);
const options = { from, to };
const translated_text = await translate(text, options);
return translated_text.text;
}
@@ -20,12 +17,12 @@ console.log(filePath);
console.log(targetFilePath);
async function processFrontMatter(block) {
var array = block.split("\n");
var translatedBlock = "";
for (var i = 0; i < array.length; i++) {
if (array[i].indexOf(":") > -1) {
var elements = array[i].split(":");
var newElement = "";
const array = block.split("\n");
let translatedBlock = "";
for (const line of array) {
let newElement = line;
if (line.indexOf(":") > -1) {
const elements = line.split(":");
if (
elements[0] == "title" ||
elements[0] == "description" ||
@@ -34,13 +31,11 @@ async function processFrontMatter(block) {
elements[0] == "categories" ||
elements[0] == "tags"
) {
var translatedElement = elements[1] ? await convert(elements[1], defaultLang, targetLang) : elements[1];
const translatedElement = elements[1]
? await convert(elements[1], defaultLang, targetLang)
: elements[1];
newElement = elements[0] + ": " + translatedElement;
} else {
newElement = array[i];
}
} else {
newElement = array[i];
}
translatedBlock += newElement + "\n";
}
@@ -48,17 +43,19 @@ async function processFrontMatter(block) {
}
async function main() {
const fileContent = fs.readFileSync(filePath, "utf8");
const fileContent = await fs.readFile(filePath, "utf8");
var array = fileContent.split("---\n");
var frontMatter = array[1];
var content = array[2];
const array = fileContent.split("---\n");
const frontMatter = array[1];
const content = array[2];
var translatedFrontMatter = await processFrontMatter(frontMatter);
var translatedContent = await convert(content, defaultLang, targetLang);
const translatedFrontMatter = await processFrontMatter(frontMatter);
const translatedContent = await convert(content, defaultLang, targetLang);
var newFileContent = "---\n" + translatedFrontMatter + "---\n" + translatedContent;
fs.writeFileSync(targetFilePath, newFileContent, "utf8");
const newFileContent =
"---\n" + translatedFrontMatter + "---\n" + translatedContent;
await fs.writeFile(targetFilePath, newFileContent, "utf8");
}
main();