Add fallback for iconv buffer decoding

This commit is contained in:
Cohee 2024-09-04 00:24:43 +03:00
parent 7040f640f4
commit 376e1f4ca2

View File

@ -9,6 +9,20 @@ const { jsonParser } = require('../express-common');
const DEEPLX_URL_DEFAULT = 'http://127.0.0.1:1188/translate';
const ONERING_URL_DEFAULT = 'http://127.0.0.1:4990/translate';
/**
* Tries to decode a Node.js Buffer to a string using iconv-lite for UTF-8.
* @param {Buffer} buffer Node.js Buffer
* @returns {string} Decoded string
*/
function decodeBuffer(buffer) {
try {
return iconv.decode(buffer, 'utf-8');
} catch (error) {
console.log('Failed to decode buffer:', error);
return buffer.toString('utf-8');
}
}
const router = express.Router();
router.post('/libre', jsonParser, async (request, response) => {
@ -89,7 +103,7 @@ router.post('/google', jsonParser, async (request, response) => {
resp.on('end', () => {
try {
const decodedData = iconv.decode(Buffer.concat(data), 'utf-8');
const decodedData = decodeBuffer(Buffer.concat(data));
const result = normaliseResponse(JSON.parse(decodedData));
console.log('Translated text: ' + result.text);
response.setHeader('Content-Type', 'text/plain; charset=utf-8');