From 98ffbd4811e1dbf1a8023421cc83515185e04be5 Mon Sep 17 00:00:00 2001 From: Tomaz Strazisnik Date: Mon, 2 Oct 2023 13:19:34 +0200 Subject: [PATCH] fix: using StringDecoder to decode fit strings --- src/fit2json.js | 10 +++++++++- test/fit2json.spec.js | 7 +++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/fit2json.js b/src/fit2json.js index 81be2ed..b27b37c 100644 --- a/src/fit2json.js +++ b/src/fit2json.js @@ -1,4 +1,12 @@ const constants = require('./constants'); +const { StringDecoder } = require('node:string_decoder'); + +/** + * Parses the buffer as a UTF-8 string. + */ +function decodeString(buffer) { + return new StringDecoder('utf8').end(Buffer.from(buffer)); +} /** * Parses one record of a FIT file @@ -169,7 +177,7 @@ function readDataField (baseType, fit, pointer, size, littleEndian) { result.push(fit.getUint8(pointer + i)); } } - return String.fromCharCode(...result); + return decodeString(result); } } diff --git a/test/fit2json.spec.js b/test/fit2json.spec.js index 48128db..b786254 100644 --- a/test/fit2json.spec.js +++ b/test/fit2json.spec.js @@ -116,6 +116,13 @@ describe('/src/fit2json', () => { const result = fit2json.readDataField(0x07, fit, 0, 6, false); expect(result).to.equal('string'); }); + + it('should decode the string base type (0x07) as UTF-8', () => { + const fit = new DataView(new Uint8Array([0xf0, 0x9f, 0x92, 0xaa]).buffer); + const result = fit2json.readDataField(0x07, fit, 0, 4, false); + expect(result).to.equal('\uD83D\uDCAA'); + }); + it('should read a byte base type (0x0D) in big endian notation', () => { const fit = new DataView(new Uint8Array([115,116,114,105,110,103]).buffer); const result = fit2json.readDataField(0x0D, fit, 0, 6, false);