@garmin/fitsdk

中文文档
21.221.0发布于 2026/11/04SEE LICENSE IN LICENSE.txtTypeScriptES Module零依赖构建来源已验证近 30 天下载 33.6万

FIT JavaScript SDK

原始使用文档
文档目录16 节
  1. FIT SDK Documentation
  2. FIT SDK Developer Forum
  3. FIT JavaScript SDK Requirements
  4. Install
  5. Decoder
  6. Usage
  7. Constructor
  8. isFIT Method
  9. Check Integrity Method
  10. Read Method
  11. Creating Streams
  12. Utils
  13. FIT_EPOCH_MS Constant
  14. convertDateTimeToDate Method
  15. Encoder
  16. Usage

Garmin - FIT JavaScript SDK

FIT SDK Documentation

The FIT SDK documentation is available at https://developer.garmin.com/fit.

FIT SDK Developer Forum

Share your knowledge, ask questions, and get the latest FIT SDK news in the FIT SDK Developer Forum.

FIT JavaScript SDK Requirements

The FIT JavaScript SDK uses ECMAScript module syntax and requires Node.js v14.0 or higher, or a browser with a compatible JavaScript runtime engine.

Install

The FIT JavaScript SDK is published as a NodeJS Package on npm as @garmin/fitsdk and can be installed with the npm cli.

npm install @garmin/fitsdk

Decoder

Usage

import { Decoder, Stream, Profile, Utils } from '@garmin/fitsdk';

const bytes = [0x0E, 0x10, 0xD9, 0x07, 0x00, 0x00, 0x00, 0x00, 0x2E, 0x46, 0x49, 0x54, 0x91, 0x33, 0x00, 0x00];

const stream = Stream.fromByteArray(bytes);
console.log("isFIT (static method): " + Decoder.isFIT(stream));

const decoder = new Decoder(stream);
console.log("isFIT (instance method): " + decoder.isFIT());
console.log("checkIntegrity: " + decoder.checkIntegrity());

const { messages, errors } = decoder.read();

console.log(errors);
console.log(messages);

Constructor

Decoder objects are created from Streams representing the binary FIT file data to be decoded. See Creating Streams for more information on constructing Stream objects.

Once a Decoder object is created it can be used to check that the Stream is a FIT file, that the FIT file is valid, and to read the contents of the FIT file.

isFIT Method

All valid FIT files should include a 12 or 14 byte file header. The 14 byte header is the preferred header size and the most common size used. Bytes 8–11 of the header contain the ASCII values ".FIT". This string can easily be spotted when opening a binary FIT file in a text or hex editor.

  Offset: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
00000000: 0E 10 43 08 78 06 09 00 2E 46 49 54 96 85 40 00    ..C.x....FIT..@.
00000010: 00 00 00 07 03 04 8C 04 04 86 07 04 86 01 02 84    ................
00000020: 02 02 84 05 02 84 00 01 00 00 19 28 7E C5 95 B0    ...........(~E.0

The isFIT method reads the file header and returns true if bytes 8–11 are equal to the ASCII values ".FIT". isFIT provides a quick way to check that the file is a FIT file before attempting to decode the file.

The Decoder class includes a static and instance version of the isFIT method.

Check Integrity Method

The checkIntegrity method performs three checks on a FIT file:

  1. Checks that bytes 8–11 of the header contain the ASCII values ".FIT".
  2. Checks that the total file size is equal to Header Size + Data Size + CRC Size.
  3. Reads the contents of the file, computes the CRC, and then checks that the computed CRC matches the file CRC.

A file must pass all three of these tests to be considered a valid FIT file. See the IsFIT(), CheckIntegrity(), and Read() Methods recipe for use-cases where the checkIntegrity method should be used and cases when it might be better to avoid it.

Read Method

The Read method decodes all messages from the input stream and returns an object containing an array of errors encountered during the decoding and a dictionary of decoded messages grouped by message type. Any exceptions encountered during decoding will be caught by the Read method and added to the array of errors.

The Read method accepts an optional options object that can be used to customize how field data is represented in the decoded messages. All options are enabled by default. Disabling options may speed up file decoding. Options may also be enabled or disabled based on how the decoded data will be used.

const { messages, errors } = decoder.read({
    mesgListener: (messageNumber, message) => {},
    mesgDefinitionListener: (mesgDefinition) => {},
    fieldDescriptionListener: (key, developerDataIdMesg, fieldDescriptionMesg) => {},
    applyScaleAndOffset: true,
    expandSubFields: true,
    expandComponents: true,
    convertTypesToStrings: true,
    convertDateTimesToDates: true,
    includeUnknownData: false,
    mergeHeartRates: true,
    decodeMemoGlobs: false,
    skipHeader: false,
    dataOnly: false,
    legacyArrayMode: false, // Deprecated
});

mesgListener = (messageNumber, message) => {}

Optional callback function that can be used to inspect or manipulate messages after they are fully decoded and all the options have been applied. The message is mutable and will be returned from the Read method in the messages dictionary.

Example mesgListener callback that tracks the field names across all Record messages.

const recordFields = new Set();

const onMesg = (messageNumber, message) => {
    if (Profile.types.mesgNum[messageNumber] === "record") {
        Object.keys(message).forEach(field => recordFields.add(field));
    }
}

const { messages, errors } = decoder.read({
    mesgListener: onMesg
});

console.log(recordFields);

mesgDefinitionListener: (mesgDefinition) => {}

Optional callback function that can be used to inspect message definitions as they are decoded from the file.

fieldDescriptionListener: (key, developerDataIdMesg, fieldDescriptionMesg) => {}

Optional callback function that can be used to inspect developer field descriptions as they are decoded from the file.

applyScaleAndOffset: true | false

When true the scale and offset values as defined in the FIT Profile are applied to the raw field values.

{
  altitude: 1587 // with a scale of 5 and offset of 500 applied
}

When false the raw field value is used.

{
  altitude: 10435 // raw value store in file
}

expandSubFields: true | false

When true subfields are created for fields as defined in the FIT Profile.

{
  event: 'rearGearChange',
  data: 16717829,
  gearChangeData:16717829 // Sub Field of data when event == 'rearGearChange'
}

When false subfields are omitted.

{
  event: 'rearGearChange',
  data: 16717829
}

expandComponents: true | false

When true field components as defined in the FIT Profile are expanded into new fields. expandSubFields must be set to true in order for subfields to be expanded

{
  event: 'rearGearChange'
  data: 16717829,
  gearChangeData:16717829, // Sub Field of data when event == 'rearGearChange
  frontGear: 2, // Expanded field of gearChangeData, bits 0-7
  frontGearNum: 53, // Expanded field of gearChangeData, bits 8-15
  rearGear: 11, // Expanded field of gearChangeData, bits 16-23
  rearGearNum: 1, // Expanded field of gearChangeData, bits 24-31
}

When false field components are not expanded.

{
  event: 'rearGearChange',
  data: 16717829,
  gearChangeData: 16717829 // Sub Field of data when event == 'rearGearChange
}

convertTypesToStrings: true | false

When true field values are converted from raw integer values to the corresponding string values as defined in the FIT Profile.

{ type:'activity'}

When false the raw integer value is used.

{ type: 4 }

convertDateTimesToDates: true | false

When true FIT Epoch values are converted to JavaScript Date objects.

{ timeCreated: {JavaScript Date object} }

When false the FIT Epoch value is used.

{ timeCreated: 995749880 }

When false the Utils.convertDateTimeToDate method may be used to convert FIT Epoch values to JavaScript Date objects.

includeUnknownData: true | false

When true unknown field values are stored in the message using the field id as the key.

{ 249: 1234} // Unknown field with an id of 249

mergeHeartRates: true | false

When true automatically merge heart rate values from HR messages into the Record messages. This option requires the applyScaleAndOffset and expandComponents options to be enabled. This option has no effect on the Record messages when no HR messages are present in the decoded messages.

decodeMemoGlobs: true | false

When true, the decoder will reconstruct strings from memoGlob messages. Each reconstructed string will overwrite the targeted message field.

skipHeader: true | false

When true, the decoder will read past the 14-byte header and ignore its contents. The decoder then assumes file data size from the size of the file's stream.

dataOnly: true | false

When true, the decoder will read the file as if the 14-byte header was not written. The decoder then assumes the file begins with a message definition and assumes file data size from the size of the file's stream.

legacyArrayMode: true | false (Deprecated)

legacyArrayMode is deprecated and will be removed by EOY 2026.

When false (default), the decoder will adhere to the profile for array fields.

Array fields will always be returned as arrays, even when there is only one element Non-array fields will always return a single value, even when there are multiple values Setting legacyArrayMode option to true will revert to pre-v21.205 behavior

Creating Streams

Stream objects contain the binary FIT data to be decoded. Stream objects can be created from byte-arrays, ArrayBuffers, and Node.js Buffers. Internally the Stream class uses an ArrayBuffer to manage the byte stream.

From a Byte Array

const streamFromByteArray = Stream.fromByteArray([0x0E, 0x10, 0xD9, 0x07, 0x00, 0x00, 0x00, 0x00, 0x2E, 0x46, 0x49, 0x54, 0x91, 0x33, 0x00, 0x00]);
console.log("isFIT: " + Decoder.isFIT(streamFromByteArray));

From an ArrayBuffer

const uint8Array = new Uint8Array([0x0E, 0x10, 0xD9, 0x07, 0x00, 0x00, 0x00, 0x00, 0x2E, 0x46, 0x49, 0x54, 0x91, 0x33, 0x00, 0x00]);
const streamFromArrayBuffer = Stream.fromArrayBuffer(uint8Array.buffer);
console.log("isFIT: " + Decoder.isFIT(streamFromArrayBuffer));

From a Node.js Buffer

const buffer = Buffer.from([0x0E, 0x10, 0xD9, 0x07, 0x00, 0x00, 0x00, 0x00, 0x2E, 0x46, 0x49, 0x54, 0x91, 0x33, 0x00, 0x00]);
const streamFromBuffer = Stream.fromBuffer(buffer);
console.log("isFIT: " + Decoder.isFIT(streamFromBuffer));

From a file using Node.js

const buf = fs.readFileSync('activity.fit');
const streamfromFileSync = Stream.fromBuffer(buf);
console.log("isFIT: " + Decoder.isFIT(streamfromFileSync));

Utils

The Utils object contains both constants and methods for working with decoded messages and fields.

FIT_EPOCH_MS Constant

The FIT_EPOCH_MS constant represents the number of milliseconds between the Unix Epoch and the FIT Epoch.

const FIT_EPOCH_MS = 631065600000;

The FIT_EPOCH_MS value can be used to convert FIT Epoch values to JavaScript Date objects.

const jsDate = new Date(fitDateTime * 1000 + Utils.FIT_EPOCH_MS);

convertDateTimeToDate Method

A convenience method for converting FIT Epoch values to JavaScript Date objects.

const jsDate = Utils.convertDateTimeToDate(fitDateTime);

Encoder

Usage

// Import the SDK
import { Encoder, Profile} from "@garmin/fitsdk";

// Create an Encoder
const encoder = new Encoder();

//
// Write messages to the output-stream
//
// The message data should match the format returned by
// the Decoder. Field names should be camelCase. The fields
// definitions can be found in the Profile.
//

// Pass the MesgNum and message data as separate parameters to the onMesg() method
encoder.onMesg(Profile.MesgNum.FILE_ID, {
  manufacturer: "development",
  product: 1,
  timeCreated: new Date(),
  type: "activity",
});

// The writeMesg() method expects the mesgNum to be included in the message data
// Internally, writeMesg() calls onMesg()
encoder.writeMesg({
  mesgNum: Profile.MesgNum.FILE_ID,
  manufacturer: "development",
  product: 1,
  timeCreated: new Date(),
  type: "activity",
});

// Unknown values in the message will be ignored by the Encoder
encoder.onMesg(Profile.MesgNum.FILE_ID, {
  manufacturer: "development",
  product: 1,
  timeCreated: new Date(),
  type: "activity",
  customField: 12345, // This value will be ignored by the Encoder
});

// Subfield values in the message will be ignored by the Encoder
encoder.onMesg(Profile.MesgNum.FILE_ID, {
  manufacturer: "development",
  product: 4440, // This is the main product field, which is a uint16
  garminProduct: "edge1050", // This value will be ignored by the Encoder, use the main field value instead
  timeCreated: new Date(),
  type: "activity",
});

// Closing the encoder returns the file as an UInt8 Array
const uint8Array = encoder.close();

// Write the file to disk,
import * as fs from "fs";
fs.writeFileSync("example.fit", uint8Array);

See the Encode Activity Recipe for a complete example of encoding a FIT Activity file using the FIT JavaScript SDK.

版本与发布记录

@garmin/fitsdk 共发布 26 个版本,首次发布于 2023/09/20;过去 12 个月发布了 14 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
21.221.0latest2026/11/0412 天前
21.218.02026/10/071 个月前
21.217.02026/09/231 个月前
21.214.02026/08/262 个月前
21.213.02026/08/123 个月前
21.212.02026/08/053 个月前

关于 @garmin/fitsdk 的常见问题

@garmin/fitsdk 是什么?

FIT JavaScript SDK

如何安装 @garmin/fitsdk?

在项目目录运行 npm install @garmin/fitsdk,或使用 pnpm add / yarn add / bun add。

@garmin/fitsdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@garmin/fitsdk 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@garmin/fitsdk 可以商用吗?

@garmin/fitsdk 使用 SEE LICENSE IN LICENSE.txt 许可。许可条款写在包内的独立文件中,请阅读该文件确认可否商用。以上为概括,不构成法律意见,请以许可原文为准。

@garmin/fitsdk 的下载量有多少?

根据 npm 官方下载统计,@garmin/fitsdk 在 2026/10/16 – 2026/11/14 这 30 天内被下载 336,340 次,日均约 11,211 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@garmin/fitsdk 还在维护吗?

最新版本 21.221.0 发布于 2026/11/04(12 天前);至今共发布 26 个版本,其中过去 12 个月发布了 14 个;首次发布于 2023/09/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。