Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
The strtok3 npm package is a streaming tokenizer for Buffer and string inputs in Node.js. It allows developers to parse through binary data or strings efficiently by defining tokenizers that can extract pieces of data sequentially. This is particularly useful for reading binary files or network streams where data structures are defined in terms of sequences or patterns of bytes.
Tokenizing fixed-length binary data
This feature allows for reading fixed-length binary data from a file. The example demonstrates reading a 32-bit unsigned integer from the beginning of a file.
const strtok3 = require('strtok3');
const { token } = require('strtok3/core');
async function parseBinaryFile(filePath) {
const tokenizer = await strtok3.fromFile(filePath);
const header = await tokenizer.readToken(token.UINT32_LE);
console.log('Header:', header);
}
Tokenizing a stream of data
This feature is used for tokenizing data directly from a stream. The example shows how to read a size as a 32-bit unsigned integer and then read a buffer of that size from the stream.
const strtok3 = require('strtok3');
const { token } = require('strtok3/core');
const fs = require('fs');
const stream = fs.createReadStream('path/to/file');
const tokenizer = strtok3.fromStream(stream);
async function readData() {
const size = await tokenizer.readToken(token.UINT32_LE);
const data = await tokenizer.readToken(new token.BufferType(size));
console.log('Data:', data.toString());
}
binary-parser is a package for building efficient binary data parsers. It is similar to strtok3 in that it helps parse binary data, but it uses a declarative approach to define the structure of the binary data instead of the imperative approach used by 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:
strtok3
can read from:
npm install strtok3
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.
[!NOTE] This module requires a Node.js ≥ 16 engine. It can also be used in a browser environment when bundled with a module bundler.
If you find this project useful and would like to support its development, consider sponsoring or contributing:
Buy me a coffee:
Use one of the methods to instantiate an abstract tokenizer:
All methods return a Tokenizer
, either directly or via a promise.
fromFile
functionCreates 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
Returns, via a promise, a tokenizer which can be used to parse a file.
import * as strtok3 from 'strtok3';
import * as Token from 'token-types';
(async () => {
const tokenizer = await strtok3.fromFile("somefile.bin");
try {
const myNumber = await tokenizer.readToken(Token.UINT8);
console.log(`My number: ${myNumber}`);
} finally {
tokenizer.close(); // Close the file
}
})();
fromStream
functionCreates a tokenizer from a Node.js readable stream.
function fromStream(stream: Readable, options?: ITokenizerOptions): Promise<ReadStreamTokenizer>
Parameter | Optional | Type | Description |
---|---|---|---|
stream | no | Readable | Stream to read from |
fileInfo | yes | IFileInfo | Provide file information |
Returns a Promise providing a tokenizer.
[!NOTE]
- Only available for Node.js engines
fromWebStream
functionCreates tokenizer from a WHATWG ReadableStream.
function fromWebStream(webStream: AnyWebByteStream, options?: ITokenizerOptions): ReadStreamTokenizer
Parameter | Optional | Type | Description |
---|---|---|---|
readableStream | no | ReadableStream | WHATWG ReadableStream to read from |
fileInfo | yes | IFileInfo | Provide file information |
Returns a Promise providing a tokenizer
import strtok3 from 'strtok3';
import * as Token from 'token-types';
strtok3.fromWebStream(readableStream).then(tokenizer => {
return tokenizer.readToken(Token.UINT8).then(myUint8Number => {
console.log(`My number: ${myUint8Number}`);
});
});
fromBuffer()
functionCreate a tokenizer from memory (Uint8Array).
function fromBuffer(uint8Array: Uint8Array, options?: ITokenizerOptions): BufferTokenizer
Parameter | Optional | Type | Description |
---|---|---|---|
uint8Array | no | Uint8Array | Uint8Array or Buffer to read from |
fileInfo | yes | IFileInfo | Provide file information |
Returns a Promise providing a tokenizer.
import * as strtok3 from 'strtok3';
const tokenizer = strtok3.fromBuffer(buffer);
tokenizer.readToken(Token.UINT8).then(myUint8Number => {
console.log(`My number: ${myUint8Number}`);
});
Tokenizer
objectThe 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;
tokenizer.ignore()
.peek
methods to preview data without advancing the read pointer.Read methods advance the stream pointer, while peek methods do not.
There are two kind of functions:
readBuffer
functionRead 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 maybe if less, mayBeLess flag was set.
peekBuffer
functionPeek (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 maybe if less, mayBeLess flag was set.
readToken
functionRead 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
functionPeek 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
functionPeek 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. |
Returns a promise with the decoded numeric value from the tokenizer-stream.
ignore
functionAdvance the offset pointer with the token number of bytes provided.
ignore(length: number): Promise<number>
Parameter | Type | Description |
---|---|---|
ignore | number | Numeric of bytes to ignore. Will advance the tokenizer.position |
Returns a promise with the decoded numeric value from the tokenizer-stream.
close
functionClean up resources, such as closing a file pointer if applicable.
Tokenizer
attributesfileInfo
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
interfaceEach 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 then the requested mayBeLess could be read. |
Example usage:
tokenizer.peekBuffer(buffer, {mayBeLess: true});
IFileInfo
interfaceProvides optional metadata about the file being tokenized.
Attribute | Type | Description |
---|---|---|
size | number | File size in bytes |
mimeType | number | MIME-type of file. |
path | number | File path |
url | boolean | File URL |
Token
objectThe token is basically a description what to read form 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.
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 } strtok3 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
})();
The diagram below illustrates the primary dependencies of strtok3
:
graph TD;
S(strtok3)-->P(peek-readable)
S(strtok3)-->TO("@tokenizer/token")
strtok3
for interpreting binary data.(The MIT License)
Copyright (c) 2024 Borewit
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
A promise based streaming tokenizer
The npm package strtok3 receives a total of 4,083,612 weekly downloads. As such, strtok3 popularity was classified as popular.
We found that strtok3 demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.