{"name":"strtok3","version":"10.2.2","description":"A promise based streaming tokenizer","author":{"name":"Borewit","url":"https://github.com/Borewit"},"funding":{"type":"github","url":"https://github.com/sponsors/Borewit"},"scripts":{"clean":"del-cli 'lib/**/*.js' 'lib/**/*.js.map' 'lib/**/*.d.ts' 'test/**/*.js' 'test/**/*.js.map'","compile-src":"tsc -p lib","compile-test":"tsc -p test","compile":"yarn run compile-src && yarn run compile-test","build":"yarn run clean && yarn run compile","eslint":"eslint lib test","lint-md":"remark -u preset-lint-recommended .","lint-ts":"biome check","lint":"yarn run lint-md && yarn run lint-ts","fix":"yarn run biome lint --write","test":"mocha","bun:test":"bun run --bun test","test-coverage":"c8 yarn run test","send-codacy":"c8 report --reporter=text-lcov | codacy-coverage","start":"yarn run compile && yarn run lint && yarn run cover-test"},"engines":{"node":">=18"},"repository":{"type":"git","url":"git+https://github.com/Borewit/strtok3.git"},"license":"MIT","type":"module","exports":{".":{"node":"./lib/index.js","default":"./lib/core.js"},"./core":"./lib/core.js"},"types":"lib/index.d.ts","bugs":{"url":"https://github.com/Borewit/strtok3/issues"},"dependencies":{"@tokenizer/token":"^0.3.0","peek-readable":"^7.0.0"},"devDependencies":{"@biomejs/biome":"^1.9.4","@types/chai":"^5.0.1","@types/chai-as-promised":"^8.0.1","@types/debug":"^4.1.12","@types/mocha":"^10.0.10","@types/node":"^22.13.8","c8":"^10.1.3","chai":"^5.2.0","chai-as-promised":"^8.0.1","del-cli":"^6.0.0","mocha":"^11.1.0","node-readable-to-web-readable-stream":"^0.4.2","remark-cli":"^12.0.1","remark-preset-lint-recommended":"^7.0.1","token-types":"^6.0.0","ts-node":"^10.9.2","typescript":"^5.8.2","uint8array-extras":"^1.4.0"},"keywords":["tokenizer","reader","token","async","promise","parser","decoder","binary","endian","uint","stream","streaming"],"packageManager":"yarn@4.6.0","_id":"strtok3@10.2.2","gitHead":"949192c92a4cbf542bfe347b0927fc6375fa03a5","homepage":"https://github.com/Borewit/strtok3#readme","_nodeVersion":"22.13.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-Xt18+h4s7Z8xyZ0tmBoRmzxcop97R4BAh+dXouUDCYn+Em+1P3qpkUfI5ueWLT8ynC5hZ+q4iPEmGG1urvQGBg==","shasum":"a4c6d78d15db02c5eb20d92af3eedf81edaf09d2","tarball":"http://registry-npm.ywwl.com/strtok3/download/strtok3-10.2.2.tgz","fileCount":17,"unpackedSize":51732,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQCt/JWuIWyCTPXESTcEDf9n92x/+0ypqVU7AsWA+9XmfwIgfZLz/HzCGxJpqiQ4F1LPKdhTnRF2NK9y4gpsnRBJsxc="}],"size":11265,"noattachment":false,"key":"/strtok3/-/strtok3-10.2.2.tgz"},"_npmUser":{"name":"borewit","email":"borewit@xs4all.nl"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/strtok3_10.2.2_1741518801623_0.4341048685436746"},"_hasShrinkwrap":false,"readme":"[![Node.js CI](https://github.com/Borewit/strtok3/actions/workflows/ci.yml/badge.svg)](https://github.com/Borewit/strtok3/actions/workflows/ci.yml)\r\n[![CodeQL](https://github.com/Borewit/strtok3/actions/workflows/codeql.yml/badge.svg?branch=master)](https://github.com/Borewit/strtok3/actions/workflows/codeql.yml)\r\n[![NPM version](https://badge.fury.io/js/strtok3.svg)](https://npmjs.org/package/strtok3)\r\n[![npm downloads](http://img.shields.io/npm/dm/strtok3.svg)](https://npmcharts.com/compare/strtok3,token-types?start=1200&interval=30)\r\n[![DeepScan grade](https://deepscan.io/api/teams/5165/projects/8526/branches/103329/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=5165&pid=8526&bid=103329)\r\n[![Known Vulnerabilities](https://snyk.io/test/github/Borewit/strtok3/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/strtok3?targetFile=package.json)\r\n[![Codacy Badge](https://api.codacy.com/project/badge/Grade/59dd6795e61949fb97066ca52e6097ef)](https://www.codacy.com/app/Borewit/strtok3?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=Borewit/strtok3&amp;utm_campaign=Badge_Grade)\r\n# strtok3\r\n\r\nA promise based streaming [*tokenizer*](#tokenizer-object) for [Node.js](http://nodejs.org) and browsers.\r\n\r\nThe `strtok3` module provides several methods for creating a [*tokenizer*](#tokenizer-object) from various input sources. \r\nDesigned for:\r\n* Seamless support in streaming environments.\r\n* Efficiently decode binary data, strings, and numbers.\r\n* Reading [predefined](https://github.com/Borewit/token-types) or custom tokens.\r\n* Offering [*tokenizers*](#tokenizer-object) for reading from [files](#method-strtok3fromfile), [streams](#fromstream-function) or [Uint8Arrays](#frombuffer-function).\r\n\r\n### Features\r\n`strtok3` can read from:\r\n* Files, using a file path as input.\r\n* Node.js [streams](https://nodejs.org/api/stream.html).\r\n* [Buffer](https://nodejs.org/api/buffer.html) or [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).\r\n* HTTP chunked transfer provided by [@tokenizer/http](https://github.com/Borewit/tokenizer-http).\r\n* [Amazon S3](https://aws.amazon.com/s3) chunks with [@tokenizer/s3](https://github.com/Borewit/tokenizer-s3).\r\n\r\n## Installation\r\n\r\n```sh\r\nnpm install strtok3\r\n```\r\n\r\n### Compatibility\r\n\r\nStarting with version 7, the module has migrated from [CommonJS](https://en.wikipedia.org/wiki/CommonJS) to [pure ECMAScript Module (ESM)](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c).\r\nThe distributed JavaScript codebase is compliant with the [ECMAScript 2020 (11th Edition)](https://en.wikipedia.org/wiki/ECMAScript_version_history#11th_Edition_%E2%80%93_ECMAScript_2020) standard.\r\n\r\nRequires a modern browser, Node.js (V8) ≥ 18 engine or Bun (JavaScriptCore) ≥ 1.2.\r\n\r\nFor TypeScript CommonJs backward compatibility, you can use [load-esm](https://github.com/Borewit/load-esm).\r\n\r\n> [!NOTE]\r\n> This module requires a [Node.js ≥ 16](https://nodejs.org/en/about/previous-releases) engine.\r\n> It can also be used in a browser environment when bundled with a module bundler.\r\n\r\n## Support the Project\r\nIf you find this project useful and would like to support its development, consider sponsoring or contributing:\r\n\r\n- [Become a sponsor to Borewit](https://github.com/sponsors/Borewit)\r\n\r\n- Buy me a coffee:\r\n\r\n  <a href=\"https://www.buymeacoffee.com/borewit\" target=\"_blank\"><img src=\"https://cdn.buymeacoffee.com/buttons/default-orange.png\" alt=\"Buy me A coffee\" height=\"41\" width=\"174\"></a>\r\n\r\n## API Documentation\r\n\r\n### strtok3 methods\r\n\r\nUse one of the methods to instantiate an [*abstract tokenizer*](#tokenizer-object):\r\n- [fromFile](#fromfile-function)*\r\n- [fromStream](#fromstream-function)*\r\n- [fromWebStream](#fromwebstream-function)\r\n- [fromBuffer](#frombuffer-function)\r\n\r\n> **_NOTE:_**  * `fromFile` and `fromStream`  only available when importing this module with Node.js\r\n\r\nAll methods return a [`Tokenizer`](#tokenizer-object), either directly or via a promise.\r\n\r\n#### `fromFile` function\r\n\r\nCreates a [*tokenizer*](#tokenizer-object) from a local file.\r\n\r\n```ts\r\nfunction fromFile(sourceFilePath: string): Promise<FileTokenizer>\r\n```  \r\n\r\n| Parameter      | Type     | Description                |\r\n|----------------|----------|----------------------------|\r\n| sourceFilePath | `string` | Path to file to read from  |\r\n\r\n> [!NOTE]\r\n> - Only available for Node.js engines\r\n> - `fromFile` automatically embeds [file-information](#file-information)\r\n\r\nReturns, via a promise, a [*tokenizer*](#tokenizer-object) which can be used to parse a file.\r\n\r\n```js\r\nimport * as strtok3 from 'strtok3';\r\nimport * as Token from 'token-types';\r\n\r\n(async () => {\r\n\r\n  const tokenizer = await strtok3.fromFile(\"somefile.bin\");\r\n         try {\r\n    const myNumber = await tokenizer.readToken(Token.UINT8);\r\n    console.log(`My number: ${myNumber}`);\r\n  } finally {\r\n    tokenizer.close(); // Close the file\r\n  }\r\n})();\r\n```\r\n\r\n#### `fromStream` function\r\n\r\nCreates a [*tokenizer*](#tokenizer-object) from a Node.js [readable stream](https://nodejs.org/api/stream.html#stream_class_stream_readable).\r\n\r\n```ts\r\nfunction fromStream(stream: Readable, options?: ITokenizerOptions): Promise<ReadStreamTokenizer>\r\n```\r\n\r\n| Parameter |  Optional | Type                                                                                 | Description              |\r\n|-----------|-----------|-------------------------|--------------------------|\r\n| stream    | no        | [Readable](https://nodejs.org/api/stream.html#stream_class_stream_readable)         | Stream to read from      |\r\n| fileInfo  | yes       | [IFileInfo](#IFileInfo) | Provide file information |\r\n\r\nReturns a Promise providing a [*tokenizer*](#tokenizer-object).\r\n\r\n> [!NOTE]\r\n> - Only available for Node.js engines\r\n\r\n#### `fromWebStream` function\r\n\r\nCreates [*tokenizer*](#tokenizer-object) from a [WHATWG ReadableStream](https://nodejs.org/api/webstreams.html#web-streams-api).\r\n\r\n```ts\r\nfunction fromWebStream(webStream: AnyWebByteStream, options?: ITokenizerOptions): ReadStreamTokenizer\r\n```\r\n\r\n| Parameter      |  Optional | Type                                                                     | Description                        |\r\n|----------------|-----------|--------------------------------------------------------------------------|------------------------------------|\r\n| readableStream | no        | [ReadableStream](https://nodejs.org/api/webstreams.html#web-streams-api) | WHATWG ReadableStream to read from |\r\n| fileInfo       | yes       | [IFileInfo](#IFileInfo)                                                  | Provide file information           |\r\n\r\nReturns a Promise providing a [*tokenizer*](#tokenizer-object)\r\n\r\n```js\r\nimport strtok3 from 'strtok3';\r\nimport * as Token from 'token-types';\r\n\r\nstrtok3.fromWebStream(readableStream).then(tokenizer => {\r\n  return tokenizer.readToken(Token.UINT8).then(myUint8Number => {\r\n    console.log(`My number: ${myUint8Number}`);\r\n  });\r\n});\r\n```\r\n\r\n#### `fromBuffer()` function\r\n\r\nCreate a tokenizer from memory ([Uint8Array](https://nodejs.org/api/buffer.html)).\r\n\r\n```ts\r\nfunction fromBuffer(uint8Array: Uint8Array, options?: ITokenizerOptions): BufferTokenizer\r\n```\r\n\r\n| Parameter  | Optional | Type                                             | Description                            |\r\n|------------|----------|--------------------------------------------------|----------------------------------------|\r\n| uint8Array | no       | [Uint8Array](https://nodejs.org/api/buffer.html) | Uint8Array or Buffer to read from      |\r\n| fileInfo   | yes      | [IFileInfo](#IFileInfo)                          | Provide file information               |\r\n\r\nReturns a Promise providing a [*tokenizer*](#tokenizer-object).\r\n\r\n```js\r\nimport * as strtok3 from 'strtok3';\r\n\r\nconst tokenizer = strtok3.fromBuffer(buffer);\r\n\r\ntokenizer.readToken(Token.UINT8).then(myUint8Number => {\r\n  console.log(`My number: ${myUint8Number}`);\r\n});\r\n```\r\n\r\n### `Tokenizer` object\r\nThe *tokenizer* is an abstraction of a [stream](https://nodejs.org/api/stream.html), file or [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), allowing _reading_ or _peeking_ from the stream.\r\nIt can also be translated in chunked reads, as done in [@tokenizer/http](https://github.com/Borewit/tokenizer-http);\r\n\r\n#### Key Features:\r\n\r\n- Supports seeking within the stream using `tokenizer.ignore()`.\r\n- Offers `peek` methods to preview data without advancing the read pointer.\r\n- Maintains the read position via tokenizer.position.\r\n\r\n#### Tokenizer functions\r\n\r\n_Read_ methods advance the stream pointer, while _peek_ methods do not.\r\n\r\nThere are two kind of functions:\r\n1. *read* methods: used to read a *token* of [Buffer](https://nodejs.org/api/buffer.html) from the [*tokenizer*](#tokenizer-object). The position of the *tokenizer-stream* will advance with the size of the token.\r\n2. *peek* methods: same as the read, but it will *not* advance the pointer. It allows to read (peek) ahead.\r\n\r\n#### `readBuffer` function\r\n\r\nRead data from the _tokenizer_ into provided \"buffer\" (`Uint8Array`).\r\n`readBuffer(buffer, options?)`\r\n\r\n```ts\r\nreadBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise<number>;\r\n```\r\n\r\n| Parameter  | Type                                                           | Description                                                                                                                                                                                                                            |\r\n|------------|----------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\r\n| buffer     | [Buffer](https://nodejs.org/api/buffer.html) &#124; Uint8Array | Target buffer to write the data read to                                                                                                                                                                                                |\r\n| options    | [IReadChunkOptions](#ireadchunkoptions)                        | An integer specifying the number of bytes to read                                                                                                                                                                                      |\r\n\r\nReturn promise with number of bytes read.\r\nThe number of bytes read maybe if less, *mayBeLess* flag was set.\r\n\r\n#### `peekBuffer` function\r\n\r\nPeek (read ahead), from [*tokenizer*](#tokenizer-object), into the buffer without advancing the stream pointer.\r\n\r\n```ts\r\npeekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise<number>;\r\n```\r\n\r\n| Parameter  | Type                                    | Description                                         |\r\n|------------|-----------------------------------------|-----------------------------------------------------|\r\n| buffer     | Buffer &#124; Uint8Array                | Target buffer to write the data read (peeked) to.   |\r\n| options    | [IReadChunkOptions](#ireadchunkoptions) | An integer specifying the number of bytes to read.  |                                                                                                                           |\r\n\r\nReturn value `Promise<number>` Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set.\r\n\r\n#### `readToken` function\r\n\r\nRead a *token* from the tokenizer-stream.\r\n\r\n```ts\r\nreadToken<Value>(token: IGetToken<Value>, position: number = this.position): Promise<Value>\r\n```  \r\n\r\n| Parameter  | Type                    | Description                                                                                                           |\r\n|------------|-------------------------|---------------------------------------------------------------------------------------------------------------------- |\r\n| token      | [IGetToken](#IGetToken) | Token to read from the tokenizer-stream.                                                                              |\r\n| position?  | number                  | Offset where to begin reading within the file. If position is null, data will be read from the current file position. |\r\n\r\nReturn value `Promise<number>`. Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set.\r\n\r\n#### `peek` function\r\n\r\nPeek a *token* from the [*tokenizer*](#tokenizer-object).\r\n\r\n```ts\r\npeekToken<Value>(token: IGetToken<Value>, position: number = this.position): Promise<Value>\r\n```\r\n\r\n| Parameter  | Type                       | Description                                                                                                             |\r\n|------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------|\r\n| token      | [IGetToken<T>](#IGetToken) | Token to read from the tokenizer-stream.                                                                                |\r\n| position?  | number                     | Offset where to begin reading within the file. If position is null, data will be read from the current file position.   |\r\n\r\nReturn a promise with the token value peeked from the [*tokenizer*](#tokenizer-object).\r\n\r\n#### `readNumber` function\r\n\r\nPeek a numeric [*token*](#token) from the [*tokenizer*](#tokenizer-object).\r\n\r\n```ts\r\nreadNumber(token: IToken<number>): Promise<number>\r\n```\r\n\r\n| Parameter  | Type                            | Description                                        |\r\n|------------|---------------------------------|----------------------------------------------------|\r\n| token      | [IGetToken<number>](#IGetToken) | Numeric token to read from the tokenizer-stream.   |\r\n\r\nReturns a promise with the decoded numeric value from the *tokenizer-stream*.\r\n\r\n#### `ignore` function\r\n\r\nAdvance the offset pointer with the token number of bytes provided.\r\n\r\n```ts\r\nignore(length: number): Promise<number>\r\n```\r\n\r\n| Parameter  | Type   | Description                                                          |\r\n|------------|--------|----------------------------------------------------------------------|\r\n| ignore     | number | Numeric of bytes to ignore. Will advance the `tokenizer.position`    |\r\n\r\nReturns a promise with the decoded numeric value from the *tokenizer-stream*.\r\n\r\n#### `close` function\r\nClean up resources, such as closing a file pointer if applicable.\r\n\r\n#### `Tokenizer` attributes\r\n\r\n- `fileInfo`\r\n\r\n  Optional attribute describing the file information, see [IFileInfo](#IFileInfo)\r\n\r\n- `position`\r\n\r\n  Pointer to the current position in the [*tokenizer*](#tokenizer-object) stream.\r\n  If a *position* is provided to a _read_ or _peek_ method, is should be, at least, equal or greater than this value.\r\n\r\n### `IReadChunkOptions` interface\r\n\r\nEach attribute is optional:\r\n\r\n| Attribute | Type    | Description                                                                                                                                                                                                                   |\r\n|-----------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\r\n| length    | number  | Requested number of bytes to read.                                                                                                                                                                                            |\r\n| position  | number  | Position where to peek from the file. If position is null, data will be read from the [current file position](#attribute-tokenizerposition). Position may not be less then [tokenizer.position](#attribute-tokenizerposition) |\r\n| mayBeLess | boolean | If and only if set, will not throw an EOF error if less then the requested *mayBeLess* could be read.                                                                                                                         |\r\n\r\nExample usage:\r\n```js\r\n  tokenizer.peekBuffer(buffer, {mayBeLess: true});\r\n```\r\n\r\n### `IFileInfo` interface\r\n\r\nProvides optional metadata about the file being tokenized.\r\n\r\n| Attribute | Type    | Description                                                                                       |\r\n|-----------|---------|---------------------------------------------------------------------------------------------------|\r\n| size      | number  | File size in bytes                                                                                |\r\n| mimeType  | number  | [MIME-type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) of file. |\r\n| path      | number  | File path                                                                                         |\r\n| url       | boolean | File URL                                                                                          |\r\n\r\n### `Token` object\r\n\r\nThe *token* is basically a description what to read form the [*tokenizer-stream*](#tokenizer-object).\r\nA basic set of *token types* can be found here: [*token-types*](https://github.com/Borewit/token-types).\r\n\r\nA token is something which implements the following interface:\r\n```ts\r\nexport interface IGetToken<T> {\r\n\r\n  /**\r\n   * Length in bytes of encoded value\r\n   */\r\n  len: number;\r\n\r\n  /**\r\n   * Decode value from buffer at offset\r\n   * @param buf Buffer to read the decoded value from\r\n   * @param off Decode offset\r\n   */\r\n  get(buf: Uint8Array, off: number): T;\r\n}\r\n```\r\nThe *tokenizer* reads `token.len` bytes from the *tokenizer-stream* into a Buffer.\r\nThe `token.get` will be called with the Buffer. `token.get` is responsible for conversion from the buffer to the desired output type.\r\n\r\n### Working with Web-API readable stream\r\nTo convert a [Web-API readable stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader) into a [Node.js readable stream]((https://nodejs.org/api/stream.html#stream_readable_streams)), you can use [readable-web-to-node-stream](https://github.com/Borewit/readable-web-to-node-stream) to convert one in another.\r\n\r\n```js\r\nimport { fromWebStream } strtok3 from 'strtok3';\r\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\r\n\r\n(async () => {\r\n\r\n  const response = await fetch(url);\r\n  const readableWebStream = response.body; // Web-API readable stream\r\n  const webStream = new ReadableWebToNodeStream(readableWebStream); // convert to Node.js readable stream\r\n\r\n  const tokenizer = fromWebStream(webStream); // And we now have tokenizer in a web environment\r\n})();\r\n```\r\n\r\n## Dependencies\r\n\r\nThe diagram below illustrates the primary dependencies of `strtok3`:\r\n\r\n```mermaid\r\ngraph TD;\r\n  S(strtok3)-->P(peek-readable)\r\n  S(strtok3)-->TO(\"@tokenizer/token\")\r\n```\r\n \r\n- [peek-readable](https://github.com/Borewit/peek-readable): Manages reading operations with peeking capabilities, allowing data to be previewed without advancing the read pointer.\r\n- [@tokenizer/token](https://github.com/Borewit/tokenizer-token): Provides token definitions and utilities used by `strtok3` for interpreting binary data.\r\n\r\n## Licence\r\n\r\nThis project is licensed under the [MIT License](LICENSE.txt). Feel free to use, modify, and distribute as needed.\r\n","publish_time":1741518801937,"maintainers":[{"name":"borewit","email":"borewit@xs4all.nl"}],"_cnpm_publish_time":1741518801937,"dist-tags":{"beta":"10.1.0-beta.5","esm":"7.0.0-alpha.9","latest":"10.7.0"}}