npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

strtok3

v10.3.4

Published

A promise based streaming tokenizer

Readme

Node.js CI CodeQL NPM version npm downloads DeepScan grade Known Vulnerabilities Codacy Badge

strtok3

A promise based streaming tokenizer for Node.js and browsers.

The strtok3 module provides several methods for creating a tokenizer from various input sources. Designed for:

Features

strtok3 can read from:

Installation

npm install strtok3

Compatibility

Starting with version 7, the module has migrated from CommonJS to pure ECMAScript Module (ESM). The distributed JavaScript codebase is compliant with the ECMAScript 2020 (11th Edition) standard.

Requires a modern browser, Node.js (V8) ≥ 18 engine or Bun (JavaScriptCore) ≥ 1.2.

For TypeScript CommonJs backward compatibility, you can use load-esm.

[!NOTE] This module requires a Node.js ≥ 16 engine. It can also be used in a browser environment when bundled with a module bundler.

Support the Project

If you find this project useful and would like to support its development, consider sponsoring or contributing:

API Documentation

strtok3 methods

Use one of the methods to instantiate an abstract tokenizer:

[!NOTE] fromFile and fromStream only available when importing this module with Node.js

All methods return a Tokenizer, either directly or via a promise.

fromBlob() function

Create a tokenizer from a Blob.

function fromBlob(blob: Blob, options?: ITokenizerOptions): BlobTokenizer

| Parameter | Optional | Type | Description | |-----------|-----------|---------------------------------------------------|----------------------------------------------------------------------------------------| | blob | no | Blob | Blob or File to read from | | options | yes | ITokenizerOptions | Tokenizer options |

Returns a tokenizer.

import { fromBlob } from 'strtok3';
import { openAsBlob } from 'node:fs';
import * as Token from 'token-types';

async function parse() {
  const blob = await openAsBlob('somefile.bin');

  const tokenizer = fromBlob(blob);

  const myUint8Number = await tokenizer.readToken(Token.UINT8);
  console.log(`My number: ${myUint8Number}`);   
}

parse();

fromBuffer() function

Create a tokenizer from memory (Uint8Array or Node.js Buffer).

function fromBuffer(uint8Array: Uint8Array, options?: ITokenizerOptions): BufferTokenizer

| Parameter | Optional | Type | Description | |------------|----------|--------------------------------------------------|-----------------------------------| | uint8Array | no | Uint8Array | Buffer or Uint8Array to read from | | options | yes | ITokenizerOptions | Tokenizer options |

Returns a tokenizer.

import { fromBuffer } from 'strtok3';
import * as Token from 'token-types';

const tokenizer = fromBuffer(buffer);

async function parse() {
  const myUint8Number = await tokenizer.readToken(Token.UINT8);
  console.log(`My number: ${myUint8Number}`);
}

parse();

fromFile function

Creates a tokenizer from a local file.

function fromFile(sourceFilePath: string): Promise<FileTokenizer>

| Parameter | Type | Description | |----------------|----------|----------------------------| | sourceFilePath | string | Path to file to read from |

[!NOTE]

  • Only available for Node.js engines
  • fromFile automatically embeds file-information

A Promise resolving to a tokenizer which can be used to parse a file.

import { fromFile } from 'strtok3';
import * as Token from 'token-types';

async function parse() {
  const tokenizer = await fromFile('somefile.bin');
  try {
    const myNumber = await tokenizer.readToken(Token.UINT8);
    console.log(`My number: ${myNumber}`);
  } finally {
    tokenizer.close(); // Close the file
  }
}

parse();

fromWebStream() function

Create a tokenizer from a WHATWG ReadableStream.

function fromWebStream(webStream: AnyWebByteStream, options?: ITokenizerOptions): ReadStreamTokenizer

| Parameter | Optional | Type | Description | |----------------|----------|--------------------------------------------------------------------------|------------------------------------| | webStream | no | ReadableStream | WHATWG ReadableStream to read from | | options | yes | ITokenizerOptions | Tokenizer options |

Returns a tokenizer.

import { fromWebStream } from 'strtok3';
import * as Token from 'token-types';

async function parse() {
  const tokenizer = fromWebStream(readableStream);
  try {
    const myUint8Number = await tokenizer.readToken(Token.UINT8);
    console.log(`My number: ${myUint8Number}`);
  } finally {
    await tokenizer.close();
  }
}

parse();

Tokenizer object

The tokenizer is an abstraction of a stream, file or Uint8Array, allowing reading or peeking from the stream. It can also be translated in chunked reads, as done in @tokenizer/http;

Key Features:

  • Supports seeking within the stream using tokenizer.ignore().
  • Offers peek methods to preview data without advancing the read pointer.
  • Maintains the read position via tokenizer.position.

Tokenizer functions

Read methods advance the stream pointer, while peek methods do not.

There are two kind of functions:

  1. read methods: used to read a token of Buffer from the tokenizer. The position of the tokenizer-stream will advance with the size of the token.
  2. peek methods: same as the read, but it will not advance the pointer. It allows to read (peek) ahead.

readBuffer function

Read data from the tokenizer into provided "buffer" (Uint8Array). readBuffer(buffer, options?)

readBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise<number>;

| Parameter | Type | Description | |------------|----------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | buffer | Buffer | Uint8Array | Target buffer to write the data read to | | options | IReadChunkOptions | An integer specifying the number of bytes to read |

Return promise with number of bytes read. The number of bytes read may be less than requested if the mayBeLess flag is set.

peekBuffer function

Peek (read ahead), from tokenizer, into the buffer without advancing the stream pointer.

peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise<number>;

| Parameter | Type | Description | |------------|-----------------------------------------|-----------------------------------------------------| | buffer | Buffer | Uint8Array | Target buffer to write the data read (peeked) to. | | options | IReadChunkOptions | An integer specifying the number of bytes to read. | |

Return value Promise<number> Promise with number of bytes read. The number of bytes read may be less if the mayBeLess flag was set.

readToken function

Read a token from the tokenizer-stream.

readToken<Value>(token: IGetToken<Value>, position: number = this.position): Promise<Value>

| Parameter | Type | Description | |------------|-------------------------|---------------------------------------------------------------------------------------------------------------------- | | token | IGetToken | Token to read from the tokenizer-stream. | | position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. |

Return value Promise<number>. Promise with number of bytes read. The number of bytes read maybe if less, mayBeLess flag was set.

peek function

Peek a token from the tokenizer.

peekToken<Value>(token: IGetToken<Value>, position: number = this.position): Promise<Value>

| Parameter | Type | Description | |------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------| | token | IGetToken | Token to read from the tokenizer-stream. | | position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. |

Return a promise with the token value peeked from the tokenizer.

readNumber function

Read a numeric token from the tokenizer.

readNumber(token: IToken<number>): Promise<number>

| Parameter | Type | Description | |------------|---------------------------------|----------------------------------------------------| | token | IGetToken | Numeric token to read from the tokenizer-stream. |

A promise resolving to a numeric value read and decoded from the tokenizer-stream.

ignore function

Advance the offset pointer with the token number of bytes provided.

ignore(length: number): Promise<number>

| Parameter | Type | Description | |------------|--------|------------------------------------------------------------------| | length | number | Number of bytes to ignore. Will advance the tokenizer.position |

A promise resolving to the number of bytes ignored from the tokenizer-stream.

close function

Clean up resources, such as closing a file pointer if applicable.

Tokenizer attributes

  • fileInfo

    Optional attribute describing the file information, see IFileInfo

  • position

    Pointer to the current position in the tokenizer stream. If a position is provided to a read or peek method, is should be, at least, equal or greater than this value.

IReadChunkOptions interface

Each attribute is optional:

| Attribute | Type | Description | |-----------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | length | number | Requested number of bytes to read. | | position | number | Position where to peek from the file. If position is null, data will be read from the current file position. Position may not be less then tokenizer.position | | mayBeLess | boolean | If and only if set, will not throw an EOF error if less than the requested mayBeLess could be read. |

Example usage:

  tokenizer.peekBuffer(buffer, {mayBeLess: true});

IFileInfo interface

Provides optional metadata about the file being tokenized.

| Attribute | Type | Description | |-----------|---------|---------------------------------------------------------------------------------------------------| | size | number | File size in bytes | | mimeType | string | MIME-type of file. | | path | string | File path | | url | string | File URL |

Token object

The token is basically a description of what to read from the tokenizer-stream. A basic set of token types can be found here: token-types.

A token is something which implements the following interface:

export interface IGetToken<T> {

  /**
   * Length in bytes of encoded value
   */
  len: number;

  /**
   * Decode value from buffer at offset
   * @param buf Buffer to read the decoded value from
   * @param off Decode offset
   */
  get(buf: Uint8Array, off: number): T;
}

The tokenizer reads token.len bytes from the tokenizer-stream into a Buffer. The token.get will be called with the Buffer. token.get is responsible for conversion from the buffer to the desired output type.

Working with Web-API readable stream

To convert a Web-API readable stream into a Node.js readable stream, you can use readable-web-to-node-stream to convert one in another.

import { fromWebStream } from 'strtok3';
import { ReadableWebToNodeStream } from 'readable-web-to-node-stream';

(async () => {

  const response = await fetch(url);
  const readableWebStream = response.body; // Web-API readable stream
  const webStream = new ReadableWebToNodeStream(readableWebStream); // convert to Node.js readable stream

  const tokenizer = fromWebStream(webStream); // And we now have tokenizer in a web environment
})();

Dependencies

Dependencies:

  • @tokenizer/token: Provides token definitions and utilities used by strtok3 for interpreting binary data.

Licence

This project is licensed under the MIT License. Feel free to use, modify, and distribute as needed.