From 376e1f4ca2f332d545fcaac124f344fc61dbe6f9 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Wed, 4 Sep 2024 00:24:43 +0300 Subject: [PATCH] Add fallback for iconv buffer decoding --- src/endpoints/translate.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/endpoints/translate.js b/src/endpoints/translate.js index 6b272e27e..20759a271 100644 --- a/src/endpoints/translate.js +++ b/src/endpoints/translate.js @@ -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');