strtok3
A promise based streaming tokenizer for Node.js and browsers. This node module is a successor of strtok2.
The strtok3
contains a few methods to turn different input into a tokenizer. Designed to
- Support a streaming environment
- Decoding of binary data, strings and numbers in mind
- Read predefined or custom tokens.
- Optimized tokenizers for reading from file, stream or buffer.
It can read from:
- A file (taking a file path as an input)
- A Node.js stream.
- A Buffer
- HTTP chunked transfer provided by @tokenizer/http.
Usage
Use one of the methods to instantiate an abstract tokenizer:
strtok3 methods
All of the strtok3 methods return a tokenizer, either directly or via a promise.
strtok3.fromFile()
Method Returns, via a promise, a tokenizer which can be used to parse a file.
const strtok3 = require('strtok3');
const Token = require('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
}
})();
strtok3.fromStream()
Method Create tokenizer from a node.js readable stream.
Parameter | Type | Description |
---|---|---|
stream | Readable | Stream to read from |
const strtok3 = require('strtok3');
const Token = require('token-types');
strtok3.fromStream(stream).then(tokenizer => {
return tokenizer.readToken(Token.UINT8).then(myUint8Number => {
console.log(`My number: ${myUint8Number}`);
});
});
Returns a tokenizer, via a Promise, which can be used to parse a buffer.
strtok3.fromBuffer()
Method Returns a tokenizer which can be used to parse a buffer.
const strtok3 = require('strtok3');
const tokenizer = strtok3.fromBuffer(buffer);
tokenizer.readToken(Token.UINT8).then(myUint8Number => {
console.log(`My number: ${myUint8Number}`);
});
Tokenizer
The tokenizer allows us to read or peek from the tokenizer-stream. The tokenizer-stream is an abstraction of a stream, file or Buffer. It can also be translated in chunked reads, as done in streaming-http-token-reader;
What is the difference with Nodejs.js stream?
- The tokenizer-stream supports jumping / seeking in a the tokenizer-stream using
tokenizer.ignore()
- In addition to read methods, it has peek methods, to read a ahead and check what is coming.
The tokenizer.position keeps tracks of
Tokenizer attributes
tokenizer.fileSize
Attribute Optional attribute of the total file or stream length in bytes
tokenizer.position
Attribute 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.
Tokenizer methods
There are to groups of methods
- 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.
- peek methods: same as the read, but it will not advance the pointer. It allows to read (peek) ahead.
tokenizer.readBuffer()
Method Read buffer from stream.
readBuffer(buffer, offset?, length?, position?, maybeless?)
Parameter | Type | Description |
---|---|---|
buffer | Buffer | Uint8Array | Target buffer to write the data read to |
offset? | number | The offset in the buffer to start writing at; if not provided, start at 0 |
length? | number | An integer specifying the number of bytes to read |
position? | number | An integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position. |
maybeless? | boolean | If set, will not throw an EOF error if the less then the requested length could be read |
Return value Promise<number>
Promise with number of bytes read
tokenizer.peekBuffer()
Method Peek (read ahead) buffer from tokenizer
peekBuffer(buffer, offset?, length?, position?, maybeless?)
Parameter | Type | Description |
---|---|---|
buffer | Buffer | Uint8Array | Target buffer to write the data read (peeked) to |
offset? | number | The offset in the buffer to start writing at; if not provided, start at 0 |
length? | number | The number of bytes to read. |
position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. |
maybeless? | boolean | If set, will not throw an EOF error if the less then the requested length could be read |
Return value Promise<number>
Promise with number of bytes read
tokenizer.readToken()
Method Read a token from the tokenizer-stream.
readToken(token, position?, maybeless?)
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. |
maybeless? | boolean | If set, will not throw an EOF error if the less then the requested length could be read. |
Return value Promise<T>
. Promise with token value read from the tokenizer-stream.
tokenizer.peekToken()
Method Peek a token from the tokenizer-stream.
peekToken(token, position?, maybeless?)
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. |
maybeless? | boolean | If set, will not throw an EOF error if the less then the requested length could be read |
Return value Promise<T>
Promise with token value peeked from the tokenizer-stream.
tokenizer.readNumber()
Method Peek a numeric token from the tokenizer-stream.
readNumber(token)
Parameter | Type | Description |
---|---|---|
token | IGetToken | Numeric token to read from the tokenizer-stream. |
Return value Promise<number>
Promise with number peeked from the tokenizer-stream.
tokenizer.ignore()
Method Peek a numeric token from the tokenizer-stream.
ignore(length)
Parameter | Type | Description |
---|---|---|
ignore | number | Numeric of bytes to ignore. Will advance the tokenizer.position
|
Return value Promise<number>
Promise with number peeked from the tokenizer-stream.
tokenizer.close()
Method Clean up resources, such as closing a file pointer if applicable.
Token
The 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: Buffer, 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.
Browser compatibility
To exclude fs based dependencies, you can use a submodule-import from 'strtok3/lib/core'.
function | 'strtok3' | 'strtok3/lib/core' |
---|---|---|
parseBuffer |
✓ | ✓ |
parseStream |
✓ | ✓ |
fromFile |
✓ |
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.
Example submodule-import:
const strtok3core = require('strtok3/lib/core'); // Submodule-import to prevent Node.js specific dependencies
const {ReadableWebToNodeStream} = require('readable-web-to-node-stream');
(async () => {
const response = await fetch(url);
const readableWebStream = response.body; // Web-API readable stream
const nodeStream = new ReadableWebToNodeStream(readableWebStream); // convert to Node.js readable stream
const tokenizer = strtok3core.fromStream(nodeStream); // And we now have tokenizer in a web environment
})();