Back to Library
Scrape Translate
js • 1/26/2026
7
const axios = require("axios");
async function translate(text, source, target) {
const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${source}&tl=${target}&dt=t&q=${encodeURIComponent(text)}`;
try {
const response = await axios.get(url, {
timeout: 30000,
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
},
});
if (response.status !== 200) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = response.data;
return data?.[0]?.[0]?.[0] || "Translation not found.";
} catch (error) {
console.error("Translation API Error:", error.message);
throw new Error(`Failed to translate text: ${error.message}`);
}
}
module.exports = { translate };