strtok3 7.0.0 → 7.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,15 +1,15 @@
1
- Copyright (c) 2017, Borewit
2
- All rights reserved.
3
-
4
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
5
- documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
6
- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
7
- persons to whom the Software is furnished to do so, subject to the following conditions:
8
-
9
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
10
- Software.
11
-
12
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
13
- WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
14
- COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
1
+ Copyright (c) 2017, Borewit
2
+ All rights reserved.
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
5
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
6
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
7
+ persons to whom the Software is furnished to do so, subject to the following conditions:
8
+
9
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
10
+ Software.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
13
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
14
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15
15
  OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,306 +1,317 @@
1
- ![Node.js CI](https://github.com/Borewit/strtok3/workflows/Node.js%20CI/badge.svg)
2
- [![NPM version](https://badge.fury.io/js/strtok3.svg)](https://npmjs.org/package/strtok3)
3
- [![npm downloads](http://img.shields.io/npm/dm/strtok3.svg)](https://npmcharts.com/compare/strtok3,token-types?start=1200&interval=30)
4
- [![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)
5
- [![Known Vulnerabilities](https://snyk.io/test/github/Borewit/strtok3/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/strtok3?targetFile=package.json)
6
- [![Total alerts](https://img.shields.io/lgtm/alerts/g/Borewit/strtok3.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Borewit/strtok3/alerts/)
7
- [![Codacy Badge](https://api.codacy.com/project/badge/Grade/59dd6795e61949fb97066ca52e6097ef)](https://www.codacy.com/app/Borewit/strtok3?utm_source=github.com&utm_medium=referral&utm_content=Borewit/strtok3&utm_campaign=Badge_Grade)
8
- [![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/Borewit/strtok3.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Borewit/strtok3/context:javascript)
9
- # strtok3
10
-
11
- A promise based streaming [*tokenizer*](#tokenizer) for [Node.js](http://nodejs.org) and browsers.
12
- This node module is a successor of [strtok2](https://github.com/Borewit/strtok2).
13
-
14
- The `strtok3` contains a few methods to turn different input into a [*tokenizer*](#tokenizer). Designed to
15
- * Support a streaming environment
16
- * Decoding of binary data, strings and numbers in mind
17
- * Read [predefined](https://github.com/Borewit/token-types) or custom tokens.
18
- * Optimized [*tokenizers*](#tokenizer) for reading from [file](#method-strtok3fromfile), [stream](#method-strtok3fromstream) or [buffer](#method-strtok3frombuffer).
19
-
20
- It can read from:
21
- * A file (taking a file path as an input)
22
- * A Node.js [stream](https://nodejs.org/api/stream.html).
23
- * A [Buffer](https://nodejs.org/api/buffer.html) or [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
24
- * HTTP chunked transfer provided by [@tokenizer/http](https://github.com/Borewit/tokenizer-http).
25
- * Chunked [Amazon S3](https://aws.amazon.com/s3) access provided by [@tokenizer/s3](https://github.com/Borewit/tokenizer-s3).
26
-
27
- ## Installation
28
-
29
- ```sh
30
- npm install strtok3
31
- ```
32
-
33
- ### Compatibility
34
-
35
- Module: version 7 migrated from [CommonJS](https://en.wikipedia.org/wiki/CommonJS) to [pure ECMAScript Module (ESM)](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c).
36
- JavaScript is compliant with [ECMAScript 2019 (ES10)](https://en.wikipedia.org/wiki/ECMAScript#10th_Edition_%E2%80%93_ECMAScript_2019).
37
- Requires Node.js ≥ 14.16 engine.
38
-
39
- ## API
40
-
41
- Use one of the methods to instantiate an [*abstract tokenizer*](#tokenizer):
42
- * [strtok3.fromFile](#method-strtok3fromfile)
43
- * [strtok3.fromStream](#method-strtok3fromstream)
44
- * [strtok3.fromBuffer](#method-strtok3fromBuffer)
45
- * [strtok3.fromUint8Array](#method-strtok3fromUint8Array)
46
-
47
- ### strtok3 methods
48
-
49
- All of the strtok3 methods return a [*tokenizer*](#tokenizer), either directly or via a promise.
50
-
51
- #### Method `strtok3.fromFile()`
52
-
53
- | Parameter | Type | Description |
54
- |-----------|-----------------------|----------------------------|
55
- | path | Path to file (string) | Path to file to read from |
56
-
57
- > __Note__: that [file-information](#file-information) is automatically added.
58
-
59
- Returns, via a promise, a [*tokenizer*](#tokenizer) which can be used to parse a file.
60
-
61
- ```js
62
- import * as strtok3 from 'strtok3';
63
- import * as Token from 'token-types';
64
-
65
- (async () => {
66
-
67
- const tokenizer = await strtok3.fromFile("somefile.bin");
68
- try {
69
- const myNumber = await tokenizer.readToken(Token.UINT8);
70
- console.log(`My number: ${myNumber}`);
71
- } finally {
72
- tokenizer.close(); // Close the file
73
- }
74
- })();
75
-
76
- ```
77
-
78
- #### Method `strtok3.fromStream()`
79
-
80
- Create [*tokenizer*](#tokenizer) from a node.js [readable stream](https://nodejs.org/api/stream.html#stream_class_stream_readable).
81
-
82
- | Parameter | Optional | Type | Description |
83
- |-----------|-----------|-----------------------------------------------------------------------------|--------------------------|
84
- | stream | no | [Readable](https://nodejs.org/api/stream.html#stream_class_stream_readable) | Stream to read from |
85
- | fileInfo | yes | [IFileInfo](#IFileInfo) | Provide file information |
86
-
87
- Returns a [*tokenizer*](#tokenizer), via a Promise, which can be used to parse a buffer.
88
-
89
- ```js
90
- import strtok3 from 'strtok3';
91
- import * as Token from 'token-types';
92
-
93
- strtok3.fromStream(stream).then(tokenizer => {
94
- return tokenizer.readToken(Token.UINT8).then(myUint8Number => {
95
- console.log(`My number: ${myUint8Number}`);
96
- });
97
- });
98
- ```
99
-
100
- #### Method `strtok3.fromBuffer()`
101
-
102
- | Parameter | Optional | Type | Description |
103
- |------------|----------|--------------------------------------------------|----------------------------------------|
104
- | uint8Array | no | [Uint8Array](https://nodejs.org/api/buffer.html) | Uint8Array or Buffer to read from |
105
- | fileInfo | yes | [IFileInfo](#IFileInfo) | Provide file information |
106
-
107
- Returns a [*tokenizer*](#tokenizer) which can be used to parse the provided buffer.
108
-
109
- ```js
110
- import * as strtok3 from 'strtok3';
111
-
112
- const tokenizer = strtok3.fromBuffer(buffer);
113
-
114
- tokenizer.readToken(Token.UINT8).then(myUint8Number => {
115
- console.log(`My number: ${myUint8Number}`);
116
- });
117
- ```
118
-
119
- ## Tokenizer
120
- The tokenizer allows us to *read* or *peek* from the *tokenizer-stream*. The *tokenizer-stream* is an abstraction of a [stream](https://nodejs.org/api/stream.html), file or [Buffer](https://nodejs.org/api/buffer.html).
121
- It can also be translated in chunked reads, as done in [@tokenizer/http](https://github.com/Borewit/tokenizer-http);
122
-
123
- What is the difference with Nodejs.js stream?
124
- * The *tokenizer-stream* supports jumping / seeking in a the *tokenizer-stream* using [`tokenizer.ignore()`](#method-tokenizerignore)
125
- * In addition to *read* methods, it has *peek* methods, to read a ahead and check what is coming.
126
-
127
- The [tokenizer.position](#attribute-tokenizerposition) keeps tracks of the read position.
128
-
129
- ### strtok3 attributes
130
-
131
- #### Attribute `tokenizer.fileInfo`
132
- Optional attribute describing the file information, see [IFileInfo](#IFileInfo)
133
-
134
- #### Attribute `tokenizer.position`
135
- Pointer to the current position in the [*tokenizer*](#tokenizer) stream.
136
- If a *position* is provided to a *read* or *peek* method, is should be, at least, equal or greater than this value.
137
-
138
- ### Tokenizer methods
139
-
140
- There are two kind of methods:
141
- 1. *read* methods: used to read a *token* of [Buffer](https://nodejs.org/api/buffer.html) from the [*tokenizer*](#tokenizer). The position of the *tokenizer-stream* will advance with the size of the token.
142
- 2. *peek* methods: same as the read, but it will *not* advance the pointer. It allows to read (peek) ahead.
143
-
144
- #### Method `tokenizer.readBuffer()`
145
-
146
- Read buffer from stream.
147
- `readBuffer(buffer, options?)`
148
-
149
- | Parameter | Type | Description |
150
- |------------|----------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
151
- | buffer | [Buffer](https://nodejs.org/api/buffer.html) | Uint8Array | Target buffer to write the data read to |
152
- | options | [IReadChunkOptions](#ireadchunkoptions) | An integer specifying the number of bytes to read |
153
-
154
- Return value `Promise<number>` Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set.
155
-
156
- #### Method `tokenizer.peekBuffer()`
157
-
158
- Peek (read ahead) buffer from [*tokenizer*](#tokenizer)
159
- `peekBuffer(buffer, options?)`
160
-
161
- | Parameter | Type | Description |
162
- |------------|-----------------------------------------|-----------------------------------------------------|
163
- | buffer | Buffer &#124; Uint8Array | Target buffer to write the data read (peeked) to. |
164
- | options | [IReadChunkOptions](#ireadchunkoptions) | An integer specifying the number of bytes to read. | |
165
-
166
- Return value `Promise<number>` Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set.
167
-
168
- #### Method `tokenizer.readToken()`
169
-
170
- Read a *token* from the tokenizer-stream.
171
- `readToken(token, position?)`
172
-
173
- | Parameter | Type | Description |
174
- |------------|-------------------------|---------------------------------------------------------------------------------------------------------------------- |
175
- | token | [IGetToken](#IGetToken) | Token to read from the tokenizer-stream. |
176
- | position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. |
177
-
178
- Return value `Promise<number>`. Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set.
179
-
180
- #### Method `tokenizer.peekToken()`
181
-
182
- Peek a *token* from the [*tokenizer*](#tokenizer).
183
- `peekToken(token, position?)`
184
-
185
- | Parameter | Type | Description |
186
- |------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------|
187
- | token | [IGetToken<T>](#IGetToken) | Token to read from the tokenizer-stream. |
188
- | position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. |
189
-
190
- Return value `Promise<T>` Promise with token value peeked from the [*tokenizer*](#tokenizer).
191
-
192
- #### Method `tokenizer.readNumber()`
193
-
194
- Peek a numeric [*token*](#token) from the [*tokenizer*](#tokenizer).
195
- `readNumber(token)`
196
-
197
- | Parameter | Type | Description |
198
- |------------|---------------------------------|----------------------------------------------------|
199
- | token | [IGetToken<number>](#IGetToken) | Numeric token to read from the tokenizer-stream. |
200
-
201
- Return value `Promise<number>` Promise with number peeked from the *tokenizer-stream*.
202
-
203
- #### Method `tokenizer.ignore()`
204
-
205
- Advanse the offset pointer with the number of bytes provided.
206
- `ignore(length)`
207
-
208
- | Parameter | Type | Description |
209
- |------------|--------|----------------------------------------------------------------------|
210
- | ignore | number | Numeric of bytes to ignore. Will advance the `tokenizer.position` |
211
-
212
- Return value `Promise<number>` Promise with number peeked from the *tokenizer-stream*.
213
-
214
- #### Method `tokenizer.close()`
215
- Clean up resources, such as closing a file pointer if applicable.
216
-
217
- ### IReadChunkOptions
218
-
219
- Each attribute is optional:
220
-
221
- | Attribute | Type | Description |
222
- |-----------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
223
- | offset | number | The offset in the buffer to start writing at; if not provided, start at 0 |
224
- | length | number | Requested number of bytes to read. |
225
- | 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) |
226
- | mayBeLess | boolean | If and only if set, will not throw an EOF error if less then the requested *mayBeLess* could be read. |
227
-
228
- Example:
229
- ```js
230
- tokenizer.peekBuffer(buffer, {mayBeLess: true});
231
- ```
232
-
233
- ## IFileInfo
234
-
235
- File information interface which describes the underlying file, each attribute is optional.
236
-
237
- | Attribute | Type | Description |
238
- |-----------|---------|---------------------------------------------------------------------------------------------------|
239
- | size | number | File size in bytes |
240
- | mimeType | number | [MIME-type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) of file. |
241
- | path | number | File path |
242
- | url | boolean | File URL |
243
-
244
- ## Token
245
-
246
- The *token* is basically a description what to read form the [*tokenizer-stream*](#tokenizer).
247
- A basic set of *token types* can be found here: [*token-types*](https://github.com/Borewit/token-types).
248
-
249
- A token is something which implements the following interface:
250
- ```ts
251
- export interface IGetToken<T> {
252
-
253
- /**
254
- * Length in bytes of encoded value
255
- */
256
- len: number;
257
-
258
- /**
259
- * Decode value from buffer at offset
260
- * @param buf Buffer to read the decoded value from
261
- * @param off Decode offset
262
- */
263
- get(buf: Buffer, off: number): T;
264
- }
265
- ```
266
- The *tokenizer* reads `token.len` bytes from the *tokenizer-stream* into a Buffer.
267
- The `token.get` will be called with the Buffer. `token.get` is responsible for conversion from the buffer to the desired output type.
268
-
269
- ## Browser compatibility
270
- To exclude fs based dependencies, you can use a submodule-import from 'strtok3/lib/core'.
271
-
272
- | function | 'strtok3' | 'strtok3/lib/core' |
273
- | ----------------------| --------------------|---------------------|
274
- | `parseBuffer` | ✓ | ✓ |
275
- | `parseStream` | ✓ | ✓ |
276
- | `fromFile` | ✓ | |
277
-
278
- ### Working with Web-API readable stream
279
- To 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.
280
-
281
- Example submodule-import:
282
- ```js
283
- import * as strtok3core from 'strtok3/core'; // Submodule-import to prevent Node.js specific dependencies
284
- import { ReadableWebToNodeStream } from 'readable-web-to-node-stream';
285
-
286
- (async () => {
287
-
288
- const response = await fetch(url);
289
- const readableWebStream = response.body; // Web-API readable stream
290
- const nodeStream = new ReadableWebToNodeStream(readableWebStream); // convert to Node.js readable stream
291
-
292
- const tokenizer = strtok3core.fromStream(nodeStream); // And we now have tokenizer in a web environment
293
- })();
294
- ```
295
-
296
- ## Licence
297
-
298
- (The MIT License)
299
-
300
- Copyright (c) 2020 Borewit
301
-
302
- 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:
303
-
304
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
305
-
306
- 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.
1
+ [![Node.js CI](https://github.com/Borewit/strtok3/actions/workflows/nodejs-ci.yml/badge.svg?branch=master)](https://github.com/Borewit/strtok3/actions/workflows/nodejs-ci.yml?query=branch%3Amaster)
2
+ [![CodeQL](https://github.com/Borewit/strtok3/actions/workflows/codeql.yml/badge.svg?branch=master)](https://github.com/Borewit/strtok3/actions/workflows/codeql.yml)
3
+ [![NPM version](https://badge.fury.io/js/strtok3.svg)](https://npmjs.org/package/strtok3)
4
+ [![npm downloads](http://img.shields.io/npm/dm/strtok3.svg)](https://npmcharts.com/compare/strtok3,token-types?start=1200&interval=30)
5
+ [![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)
6
+ [![Known Vulnerabilities](https://snyk.io/test/github/Borewit/strtok3/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/strtok3?targetFile=package.json)
7
+ [![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)
8
+ # strtok3
9
+
10
+ A promise based streaming [*tokenizer*](#tokenizer) for [Node.js](http://nodejs.org) and browsers.
11
+ This node module is a successor of [strtok2](https://github.com/Borewit/strtok2).
12
+
13
+ The `strtok3` contains a few methods to turn different input into a [*tokenizer*](#tokenizer). Designed to
14
+ * Support a streaming environment
15
+ * Decoding of binary data, strings and numbers in mind
16
+ * Read [predefined](https://github.com/Borewit/token-types) or custom tokens.
17
+ * Optimized [*tokenizers*](#tokenizer) for reading from [file](#method-strtok3fromfile), [stream](#method-strtok3fromstream) or [buffer](#method-strtok3frombuffer).
18
+
19
+ It can read from:
20
+ * A file (taking a file path as an input)
21
+ * A Node.js [stream](https://nodejs.org/api/stream.html).
22
+ * A [Buffer](https://nodejs.org/api/buffer.html) or [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
23
+ * HTTP chunked transfer provided by [@tokenizer/http](https://github.com/Borewit/tokenizer-http).
24
+ * Chunked [Amazon S3](https://aws.amazon.com/s3) access provided by [@tokenizer/s3](https://github.com/Borewit/tokenizer-s3).
25
+
26
+ ## Installation
27
+
28
+ ```sh
29
+ npm install strtok3
30
+ ```
31
+
32
+ ### Compatibility
33
+
34
+ Module: version 7 migrated from [CommonJS](https://en.wikipedia.org/wiki/CommonJS) to [pure ECMAScript Module (ESM)](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c).
35
+ JavaScript is compliant with [ECMAScript 2019 (ES10)](https://en.wikipedia.org/wiki/ECMAScript#10th_Edition_%E2%80%93_ECMAScript_2019).
36
+ Requires Node.js ≥ 16 engine.
37
+
38
+ ## API
39
+
40
+ Use one of the methods to instantiate an [*abstract tokenizer*](#tokenizer):
41
+ * [strtok3.fromFile](#method-strtok3fromfile)
42
+ * [strtok3.fromStream](#method-strtok3fromstream)
43
+ * [strtok3.fromWeb](#method-strtok3fromwebstream)
44
+ * [strtok3.fromBuffer](#method-strtok3fromBuffer)
45
+ * [strtok3.fromUint8Array](#method-strtok3fromUint8Array)
46
+
47
+ ### strtok3 methods
48
+
49
+ All of the strtok3 methods return a [*tokenizer*](#tokenizer), either directly or via a promise.
50
+
51
+ #### Method `strtok3.fromFile()`
52
+
53
+ | Parameter | Type | Description |
54
+ |-----------|-----------------------|----------------------------|
55
+ | path | Path to file (string) | Path to file to read from |
56
+
57
+ > __Note__: that [file-information](#file-information) is automatically added.
58
+
59
+ Returns, via a promise, a [*tokenizer*](#tokenizer) which can be used to parse a file.
60
+
61
+ ```js
62
+ import * as strtok3 from 'strtok3';
63
+ import * as Token from 'token-types';
64
+
65
+ (async () => {
66
+
67
+ const tokenizer = await strtok3.fromFile("somefile.bin");
68
+ try {
69
+ const myNumber = await tokenizer.readToken(Token.UINT8);
70
+ console.log(`My number: ${myNumber}`);
71
+ } finally {
72
+ tokenizer.close(); // Close the file
73
+ }
74
+ })();
75
+
76
+ ```
77
+
78
+ #### Method `strtok3.fromStream()`
79
+
80
+ Create [*tokenizer*](#tokenizer) from a Node.js [readable stream](https://nodejs.org/api/stream.html#stream_class_stream_readable).
81
+
82
+ | Parameter | Optional | Type | Description |
83
+ |-----------|-----------|-----------------------------------------------------------------------------|--------------------------|
84
+ | stream | no | [Readable](https://nodejs.org/api/stream.html#stream_class_stream_readable) | Stream to read from |
85
+ | fileInfo | yes | [IFileInfo](#IFileInfo) | Provide file information |
86
+
87
+ Returns a Promise providing a [*tokenizer*](#tokenizer).
88
+
89
+ #### Method `strtok3.fromWebStream()`
90
+
91
+ Create [*tokenizer*](#tokenizer) from a [WHATWG ReadableStream](https://nodejs.org/api/webstreams.html#web-streams-api).
92
+
93
+ | Parameter | Optional | Type | Description |
94
+ |----------------|-----------|--------------------------------------------------------------------------|------------------------------------|
95
+ | readableStream | no | [ReadableStream](https://nodejs.org/api/webstreams.html#web-streams-api) | WHATWG ReadableStream to read from |
96
+ | fileInfo | yes | [IFileInfo](#IFileInfo) | Provide file information |
97
+
98
+ Returns a Promise providing a [*tokenizer*](#tokenizer)
99
+
100
+ ```js
101
+ import strtok3 from 'strtok3';
102
+ import * as Token from 'token-types';
103
+
104
+ strtok3.fromWebStream(readableStream).then(tokenizer => {
105
+ return tokenizer.readToken(Token.UINT8).then(myUint8Number => {
106
+ console.log(`My number: ${myUint8Number}`);
107
+ });
108
+ });
109
+ ```
110
+
111
+ #### Method `strtok3.fromBuffer()`
112
+
113
+ | Parameter | Optional | Type | Description |
114
+ |------------|----------|--------------------------------------------------|----------------------------------------|
115
+ | uint8Array | no | [Uint8Array](https://nodejs.org/api/buffer.html) | Uint8Array or Buffer to read from |
116
+ | fileInfo | yes | [IFileInfo](#IFileInfo) | Provide file information |
117
+
118
+ Returns a Promise providing a [*tokenizer*](#tokenizer).
119
+
120
+ ```js
121
+ import * as strtok3 from 'strtok3';
122
+
123
+ const tokenizer = strtok3.fromBuffer(buffer);
124
+
125
+ tokenizer.readToken(Token.UINT8).then(myUint8Number => {
126
+ console.log(`My number: ${myUint8Number}`);
127
+ });
128
+ ```
129
+
130
+ ## Tokenizer
131
+ The tokenizer allows us to *read* or *peek* from the *tokenizer-stream*. The *tokenizer-stream* 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).
132
+ It can also be translated in chunked reads, as done in [@tokenizer/http](https://github.com/Borewit/tokenizer-http);
133
+
134
+ What is the difference with Nodejs.js stream?
135
+ * The *tokenizer-stream* supports jumping / seeking in a the *tokenizer-stream* using [`tokenizer.ignore()`](#method-tokenizerignore)
136
+ * In addition to *read* methods, it has *peek* methods, to read a ahead and check what is coming.
137
+
138
+ The [tokenizer.position](#attribute-tokenizerposition) keeps tracks of the read position.
139
+
140
+ ### strtok3 attributes
141
+
142
+ #### Attribute `tokenizer.fileInfo`
143
+ Optional attribute describing the file information, see [IFileInfo](#IFileInfo)
144
+
145
+ #### Attribute `tokenizer.position`
146
+ Pointer to the current position in the [*tokenizer*](#tokenizer) stream.
147
+ If a *position* is provided to a *read* or *peek* method, is should be, at least, equal or greater than this value.
148
+
149
+ ### Tokenizer methods
150
+
151
+ There are two kind of methods:
152
+ 1. *read* methods: used to read a *token* of [Buffer](https://nodejs.org/api/buffer.html) from the [*tokenizer*](#tokenizer). The position of the *tokenizer-stream* will advance with the size of the token.
153
+ 2. *peek* methods: same as the read, but it will *not* advance the pointer. It allows to read (peek) ahead.
154
+
155
+ #### Method `tokenizer.readBuffer()`
156
+
157
+ Read buffer from stream.
158
+ `readBuffer(buffer, options?)`
159
+
160
+ | Parameter | Type | Description |
161
+ |------------|----------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
162
+ | buffer | [Buffer](https://nodejs.org/api/buffer.html) &#124; Uint8Array | Target buffer to write the data read to |
163
+ | options | [IReadChunkOptions](#ireadchunkoptions) | An integer specifying the number of bytes to read |
164
+
165
+ Return value `Promise<number>` Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set.
166
+
167
+ #### Method `tokenizer.peekBuffer()`
168
+
169
+ Peek (read ahead) buffer from [*tokenizer*](#tokenizer)
170
+ `peekBuffer(buffer, options?)`
171
+
172
+ | Parameter | Type | Description |
173
+ |------------|-----------------------------------------|-----------------------------------------------------|
174
+ | buffer | Buffer &#124; Uint8Array | Target buffer to write the data read (peeked) to. |
175
+ | options | [IReadChunkOptions](#ireadchunkoptions) | An integer specifying the number of bytes to read. | |
176
+
177
+ Return value `Promise<number>` Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set.
178
+
179
+ #### Method `tokenizer.readToken()`
180
+
181
+ Read a *token* from the tokenizer-stream.
182
+ `readToken(token, position?)`
183
+
184
+ | Parameter | Type | Description |
185
+ |------------|-------------------------|---------------------------------------------------------------------------------------------------------------------- |
186
+ | token | [IGetToken](#IGetToken) | Token to read from the tokenizer-stream. |
187
+ | position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. |
188
+
189
+ Return value `Promise<number>`. Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set.
190
+
191
+ #### Method `tokenizer.peekToken()`
192
+
193
+ Peek a *token* from the [*tokenizer*](#tokenizer).
194
+ `peekToken(token, position?)`
195
+
196
+ | Parameter | Type | Description |
197
+ |------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------|
198
+ | token | [IGetToken<T>](#IGetToken) | Token to read from the tokenizer-stream. |
199
+ | position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. |
200
+
201
+ Return value `Promise<T>` Promise with token value peeked from the [*tokenizer*](#tokenizer).
202
+
203
+ #### Method `tokenizer.readNumber()`
204
+
205
+ Peek a numeric [*token*](#token) from the [*tokenizer*](#tokenizer).
206
+ `readNumber(token)`
207
+
208
+ | Parameter | Type | Description |
209
+ |------------|---------------------------------|----------------------------------------------------|
210
+ | token | [IGetToken<number>](#IGetToken) | Numeric token to read from the tokenizer-stream. |
211
+
212
+ Return value `Promise<number>` Promise with number peeked from the *tokenizer-stream*.
213
+
214
+ #### Method `tokenizer.ignore()`
215
+
216
+ Advance the offset pointer with the number of bytes provided.
217
+ `ignore(length)`
218
+
219
+ | Parameter | Type | Description |
220
+ |------------|--------|----------------------------------------------------------------------|
221
+ | ignore | number | Numeric of bytes to ignore. Will advance the `tokenizer.position` |
222
+
223
+ Return value `Promise<number>` Promise with number peeked from the *tokenizer-stream*.
224
+
225
+ #### Method `tokenizer.close()`
226
+ Clean up resources, such as closing a file pointer if applicable.
227
+
228
+ ### IReadChunkOptions
229
+
230
+ Each attribute is optional:
231
+
232
+ | Attribute | Type | Description |
233
+ |-----------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
234
+ | offset | number | The offset in the buffer to start writing at; if not provided, start at 0 |
235
+ | length | number | Requested number of bytes to read. |
236
+ | 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) |
237
+ | mayBeLess | boolean | If and only if set, will not throw an EOF error if less then the requested *mayBeLess* could be read. |
238
+
239
+ Example:
240
+ ```js
241
+ tokenizer.peekBuffer(buffer, {mayBeLess: true});
242
+ ```
243
+
244
+ ## IFileInfo
245
+
246
+ File information interface which describes the underlying file, each attribute is optional.
247
+
248
+ | Attribute | Type | Description |
249
+ |-----------|---------|---------------------------------------------------------------------------------------------------|
250
+ | size | number | File size in bytes |
251
+ | mimeType | number | [MIME-type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) of file. |
252
+ | path | number | File path |
253
+ | url | boolean | File URL |
254
+
255
+ ## Token
256
+
257
+ The *token* is basically a description what to read form the [*tokenizer-stream*](#tokenizer).
258
+ A basic set of *token types* can be found here: [*token-types*](https://github.com/Borewit/token-types).
259
+
260
+ A token is something which implements the following interface:
261
+ ```ts
262
+ export interface IGetToken<T> {
263
+
264
+ /**
265
+ * Length in bytes of encoded value
266
+ */
267
+ len: number;
268
+
269
+ /**
270
+ * Decode value from buffer at offset
271
+ * @param buf Buffer to read the decoded value from
272
+ * @param off Decode offset
273
+ */
274
+ get(buf: Uint8Array, off: number): T;
275
+ }
276
+ ```
277
+ The *tokenizer* reads `token.len` bytes from the *tokenizer-stream* into a Buffer.
278
+ The `token.get` will be called with the Buffer. `token.get` is responsible for conversion from the buffer to the desired output type.
279
+
280
+ ## Browser compatibility
281
+ To exclude fs based dependencies, you can use a submodule-import from 'strtok3/lib/core'.
282
+
283
+ | function | 'strtok3' | 'strtok3/lib/core' |
284
+ | ----------------------| --------------------|---------------------|
285
+ | `parseBuffer` | ✓ | ✓ |
286
+ | `parseStream` | ✓ | ✓ |
287
+ | `fromFile` | ✓ | |
288
+
289
+ ### Working with Web-API readable stream
290
+ To 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.
291
+
292
+ Example submodule-import:
293
+ ```js
294
+ import * as strtok3core from 'strtok3/core'; // Submodule-import to prevent Node.js specific dependencies
295
+ import { ReadableWebToNodeStream } from 'readable-web-to-node-stream';
296
+
297
+ (async () => {
298
+
299
+ const response = await fetch(url);
300
+ const readableWebStream = response.body; // Web-API readable stream
301
+ const nodeStream = new ReadableWebToNodeStream(readableWebStream); // convert to Node.js readable stream
302
+
303
+ const tokenizer = strtok3core.fromStream(nodeStream); // And we now have tokenizer in a web environment
304
+ })();
305
+ ```
306
+
307
+ ## Licence
308
+
309
+ (The MIT License)
310
+
311
+ Copyright (c) 2020 Borewit
312
+
313
+ 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:
314
+
315
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
316
+
317
+ 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.
@@ -1,5 +1,4 @@
1
1
  import { EndOfStreamError } from 'peek-readable';
2
- import { Buffer } from 'node:buffer';
3
2
  /**
4
3
  * Core tokenizer
5
4
  */
@@ -19,7 +18,7 @@ export class AbstractTokenizer {
19
18
  * @returns Promise with token data
20
19
  */
21
20
  async readToken(token, position = this.position) {
22
- const uint8Array = Buffer.alloc(token.len);
21
+ const uint8Array = new Uint8Array(token.len);
23
22
  const len = await this.readBuffer(uint8Array, { position });
24
23
  if (len < token.len)
25
24
  throw new EndOfStreamError();
@@ -32,7 +31,7 @@ export class AbstractTokenizer {
32
31
  * @returns Promise with token data
33
32
  */
34
33
  async peekToken(token, position = this.position) {
35
- const uint8Array = Buffer.alloc(token.len);
34
+ const uint8Array = new Uint8Array(token.len);
36
35
  const len = await this.peekBuffer(uint8Array, { position });
37
36
  if (len < token.len)
38
37
  throw new EndOfStreamError();
@@ -1,8 +1,9 @@
1
1
  import { AbstractTokenizer } from './AbstractTokenizer.js';
2
2
  import { IFileInfo, IReadChunkOptions } from './types.js';
3
+ import { FileHandle } from 'node:fs/promises';
3
4
  export declare class FileTokenizer extends AbstractTokenizer {
4
- private fd;
5
- constructor(fd: number, fileInfo: IFileInfo);
5
+ private fileHandle;
6
+ constructor(fileHandle: FileHandle, fileInfo: IFileInfo);
6
7
  /**
7
8
  * Read buffer from file
8
9
  * @param uint8Array - Uint8Array to write result to
@@ -1,10 +1,10 @@
1
1
  import { AbstractTokenizer } from './AbstractTokenizer.js';
2
2
  import { EndOfStreamError } from 'peek-readable';
3
- import * as fs from './FsPromise.js';
3
+ import { open as fsOpen } from 'node:fs/promises';
4
4
  export class FileTokenizer extends AbstractTokenizer {
5
- constructor(fd, fileInfo) {
5
+ constructor(fileHandle, fileInfo) {
6
6
  super(fileInfo);
7
- this.fd = fd;
7
+ this.fileHandle = fileHandle;
8
8
  }
9
9
  /**
10
10
  * Read buffer from file
@@ -15,7 +15,7 @@ export class FileTokenizer extends AbstractTokenizer {
15
15
  async readBuffer(uint8Array, options) {
16
16
  const normOptions = this.normalizeOptions(uint8Array, options);
17
17
  this.position = normOptions.position;
18
- const res = await fs.read(this.fd, uint8Array, normOptions.offset, normOptions.length, normOptions.position);
18
+ const res = await this.fileHandle.read(uint8Array, normOptions.offset, normOptions.length, normOptions.position);
19
19
  this.position += res.bytesRead;
20
20
  if (res.bytesRead < normOptions.length && (!options || !options.mayBeLess)) {
21
21
  throw new EndOfStreamError();
@@ -30,21 +30,18 @@ export class FileTokenizer extends AbstractTokenizer {
30
30
  */
31
31
  async peekBuffer(uint8Array, options) {
32
32
  const normOptions = this.normalizeOptions(uint8Array, options);
33
- const res = await fs.read(this.fd, uint8Array, normOptions.offset, normOptions.length, normOptions.position);
33
+ const res = await this.fileHandle.read(uint8Array, normOptions.offset, normOptions.length, normOptions.position);
34
34
  if ((!normOptions.mayBeLess) && res.bytesRead < normOptions.length) {
35
35
  throw new EndOfStreamError();
36
36
  }
37
37
  return res.bytesRead;
38
38
  }
39
39
  async close() {
40
- return fs.close(this.fd);
40
+ return this.fileHandle.close();
41
41
  }
42
42
  }
43
43
  export async function fromFile(sourceFilePath) {
44
- const stat = await fs.stat(sourceFilePath);
45
- if (!stat.isFile) {
46
- throw new Error(`File not a file: ${sourceFilePath}`);
47
- }
48
- const fd = await fs.open(sourceFilePath, 'r');
49
- return new FileTokenizer(fd, { path: sourceFilePath, size: stat.size });
44
+ const fileHandle = await fsOpen(sourceFilePath, 'r');
45
+ const stat = await fileHandle.stat();
46
+ return new FileTokenizer(fileHandle, { path: sourceFilePath, size: stat.size });
50
47
  }
@@ -1,10 +1,9 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
1
  import { AbstractTokenizer } from './AbstractTokenizer.js';
3
- import { Readable } from 'node:stream';
2
+ import { IStreamReader } from 'peek-readable';
4
3
  import { IFileInfo, IReadChunkOptions } from './types.js';
5
4
  export declare class ReadStreamTokenizer extends AbstractTokenizer {
6
5
  private streamReader;
7
- constructor(stream: Readable, fileInfo?: IFileInfo);
6
+ constructor(streamReader: IStreamReader, fileInfo?: IFileInfo);
8
7
  /**
9
8
  * Get file information, an HTTP-client may implement this doing a HEAD request
10
9
  * @return Promise with file information
@@ -1,10 +1,10 @@
1
1
  import { AbstractTokenizer } from './AbstractTokenizer.js';
2
- import { EndOfStreamError, StreamReader } from 'peek-readable';
2
+ import { EndOfStreamError } from 'peek-readable';
3
3
  const maxBufferSize = 256000;
4
4
  export class ReadStreamTokenizer extends AbstractTokenizer {
5
- constructor(stream, fileInfo) {
5
+ constructor(streamReader, fileInfo) {
6
6
  super(fileInfo);
7
- this.streamReader = new StreamReader(stream);
7
+ this.streamReader = streamReader;
8
8
  }
9
9
  /**
10
10
  * Get file information, an HTTP-client may implement this doing a HEAD request
package/lib/core.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
1
  import { ReadStreamTokenizer } from './ReadStreamTokenizer.js';
3
- import { Readable } from 'node:stream';
4
2
  import { BufferTokenizer } from './BufferTokenizer.js';
5
3
  import { IFileInfo } from './types.js';
4
+ import type { ReadableStream } from 'node:stream/web';
5
+ import type { Readable } from 'node:stream';
6
6
  export { EndOfStreamError } from 'peek-readable';
7
7
  export { ITokenizer, IFileInfo } from './types.js';
8
8
  export { IToken, IGetToken } from '@tokenizer/token';
@@ -14,6 +14,14 @@ export { IToken, IGetToken } from '@tokenizer/token';
14
14
  * @returns ReadStreamTokenizer
15
15
  */
16
16
  export declare function fromStream(stream: Readable, fileInfo?: IFileInfo): ReadStreamTokenizer;
17
+ /**
18
+ * Construct ReadStreamTokenizer from given ReadableStream (WebStream API).
19
+ * Will set fileSize, if provided given Stream has set the .path property/
20
+ * @param webStream - Read from Node.js Stream.Readable
21
+ * @param fileInfo - Pass the file information, like size and MIME-type of the corresponding stream.
22
+ * @returns ReadStreamTokenizer
23
+ */
24
+ export declare function fromWebStream(webStream: ReadableStream<Uint8Array>, fileInfo?: IFileInfo): ReadStreamTokenizer;
17
25
  /**
18
26
  * Construct ReadStreamTokenizer from given Buffer.
19
27
  * @param uint8Array - Uint8Array to tokenize
package/lib/core.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ReadStreamTokenizer } from './ReadStreamTokenizer.js';
2
2
  import { BufferTokenizer } from './BufferTokenizer.js';
3
+ import { StreamReader, WebStreamReader } from 'peek-readable';
3
4
  export { EndOfStreamError } from 'peek-readable';
4
5
  /**
5
6
  * Construct ReadStreamTokenizer from given Stream.
@@ -10,7 +11,18 @@ export { EndOfStreamError } from 'peek-readable';
10
11
  */
11
12
  export function fromStream(stream, fileInfo) {
12
13
  fileInfo = fileInfo ? fileInfo : {};
13
- return new ReadStreamTokenizer(stream, fileInfo);
14
+ return new ReadStreamTokenizer(new StreamReader(stream), fileInfo);
15
+ }
16
+ /**
17
+ * Construct ReadStreamTokenizer from given ReadableStream (WebStream API).
18
+ * Will set fileSize, if provided given Stream has set the .path property/
19
+ * @param webStream - Read from Node.js Stream.Readable
20
+ * @param fileInfo - Pass the file information, like size and MIME-type of the corresponding stream.
21
+ * @returns ReadStreamTokenizer
22
+ */
23
+ export function fromWebStream(webStream, fileInfo) {
24
+ fileInfo = fileInfo ? fileInfo : {};
25
+ return new ReadStreamTokenizer(new WebStreamReader(webStream), fileInfo);
14
26
  }
15
27
  /**
16
28
  * Construct ReadStreamTokenizer from given Buffer.
package/lib/index.d.ts CHANGED
@@ -1,9 +1,8 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
1
  import { Readable } from 'node:stream';
3
2
  import { ReadStreamTokenizer } from './ReadStreamTokenizer.js';
4
3
  import * as core from './core.js';
5
4
  export { fromFile } from './FileTokenizer.js';
6
- export { ITokenizer, EndOfStreamError, fromBuffer, IFileInfo } from './core.js';
5
+ export { ITokenizer, EndOfStreamError, fromBuffer, fromWebStream, IFileInfo } from './core.js';
7
6
  export { IToken, IGetToken } from '@tokenizer/token';
8
7
  /**
9
8
  * Construct ReadStreamTokenizer from given Stream.
package/lib/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import * as fs from './FsPromise.js';
1
+ import { stat as fsStat } from 'node:fs/promises';
2
2
  import * as core from './core.js';
3
3
  export { fromFile } from './FileTokenizer.js';
4
- export { EndOfStreamError, fromBuffer } from './core.js';
4
+ export { EndOfStreamError, fromBuffer, fromWebStream } from './core.js';
5
5
  /**
6
6
  * Construct ReadStreamTokenizer from given Stream.
7
7
  * Will set fileSize, if provided given Stream has set the .path property.
@@ -12,7 +12,7 @@ export { EndOfStreamError, fromBuffer } from './core.js';
12
12
  export async function fromStream(stream, fileInfo) {
13
13
  fileInfo = fileInfo ? fileInfo : {};
14
14
  if (stream.path) {
15
- const stat = await fs.stat(stream.path);
15
+ const stat = await fsStat(stream.path);
16
16
  fileInfo.path = stream.path;
17
17
  fileInfo.size = stat.size;
18
18
  }
package/lib/types.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
1
  import { IGetToken } from '@tokenizer/token';
3
2
  export interface IFileInfo {
4
3
  /**
@@ -57,14 +56,14 @@ export interface ITokenizer {
57
56
  * @param options - Read behaviour options
58
57
  * @returns Promise with number of bytes read
59
58
  */
60
- peekBuffer(buffer: Buffer, options?: IReadChunkOptions): Promise<number>;
59
+ peekBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise<number>;
61
60
  /**
62
61
  * Peek (read ahead) buffer from tokenizer
63
62
  * @param buffer - Target buffer to fill with data peeked from the tokenizer-stream
64
63
  * @param options - Additional read options
65
64
  * @returns Promise with number of bytes read
66
65
  */
67
- readBuffer(buffer: Buffer, options?: IReadChunkOptions): Promise<number>;
66
+ readBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise<number>;
68
67
  /**
69
68
  * Peek a token from the tokenizer-stream.
70
69
  * @param token - Token to peek from the tokenizer-stream.
package/package.json CHANGED
@@ -1,94 +1,100 @@
1
- {
2
- "name": "strtok3",
3
- "version": "7.0.0",
4
- "description": "A promise based streaming tokenizer",
5
- "author": {
6
- "name": "Borewit",
7
- "url": "https://github.com/Borewit"
8
- },
9
- "funding": {
10
- "type": "github",
11
- "url": "https://github.com/sponsors/Borewit"
12
- },
13
- "scripts": {
14
- "clean": "del-cli lib/**/*.js lib/**/*.js.map lib/**/*.d.ts test/**/*.js test/**/*.js.map",
15
- "compile-src": "tsc -p lib",
16
- "compile-test": "tsc -p test",
17
- "compile": "npm run compile-src && npm run compile-test",
18
- "build": "npm run clean && npm run compile",
19
- "eslint": "eslint lib test --ext .ts --ignore-pattern *.d.ts",
20
- "lint-md": "remark -u preset-lint-recommended .",
21
- "lint": "npm run lint-md && npm run eslint",
22
- "fix": "eslint lib test --ext .ts --ignore-pattern *.d.ts --fix",
23
- "test": "mocha",
24
- "test-coverage": "c8 npm run test",
25
- "send-codacy": "c8 report --reporter=text-lcov | codacy-coverage",
26
- "start": "npm run compile && npm run lint && npm run cover-test"
27
- },
28
- "engines": {
29
- "node": ">=14.16"
30
- },
31
- "repository": {
32
- "type": "git",
33
- "url": "https://github.com/Borewit/strtok3.git"
34
- },
35
- "license": "MIT",
36
- "type": "module",
37
- "exports": {
38
- ".": {
39
- "node": "./lib/index.js",
40
- "default": "./lib/core.js"
41
- },
42
- "./core": "./lib/core.js"
43
- },
44
- "types": "lib/index.d.ts",
45
- "files": [
46
- "lib/**/*.js",
47
- "lib/**/*.d.ts"
48
- ],
49
- "bugs": {
50
- "url": "https://github.com/Borewit/strtok3/issues"
51
- },
52
- "devDependencies": {
53
- "@types/chai": "^4.3.1",
54
- "@types/debug": "^4.1.7",
55
- "@types/mocha": "^9.1.0",
56
- "@types/node": "^18.6.3",
57
- "@typescript-eslint/eslint-plugin": "^5.32.0",
58
- "@typescript-eslint/parser": "^5.32.0",
59
- "c8": "^7.12.0",
60
- "chai": "^4.3.6",
61
- "del-cli": "^5.0.0",
62
- "eslint": "^8.21.0",
63
- "eslint-config-prettier": "^8.5.0",
64
- "eslint-import-resolver-typescript": "^3.4.0",
65
- "eslint-plugin-import": "^2.26.0",
66
- "eslint-plugin-jsdoc": "^39.3.4",
67
- "eslint-plugin-node": "^11.1.0",
68
- "eslint-plugin-unicorn": "^43.0.2",
69
- "mocha": "^10.0.0",
70
- "remark-cli": "^11.0.0",
71
- "remark-preset-lint-recommended": "^6.1.2",
72
- "token-types": "^5.0.0",
73
- "ts-node": "^10.9.1",
74
- "typescript": "^4.7.4"
75
- },
76
- "dependencies": {
77
- "@tokenizer/token": "^0.3.0",
78
- "peek-readable": "^5.0.0"
79
- },
80
- "keywords": [
81
- "tokenizer",
82
- "reader",
83
- "token",
84
- "async",
85
- "promise",
86
- "parser",
87
- "decoder",
88
- "binary",
89
- "endian",
90
- "uint",
91
- "stream",
92
- "streaming"
93
- ]
94
- }
1
+ {
2
+ "name": "strtok3",
3
+ "version": "7.1.1",
4
+ "description": "A promise based streaming tokenizer",
5
+ "author": {
6
+ "name": "Borewit",
7
+ "url": "https://github.com/Borewit"
8
+ },
9
+ "funding": {
10
+ "type": "github",
11
+ "url": "https://github.com/sponsors/Borewit"
12
+ },
13
+ "scripts": {
14
+ "clean": "del-cli lib/**/*.js lib/**/*.js.map lib/**/*.d.ts test/**/*.js test/**/*.js.map",
15
+ "compile-src": "tsc -p lib",
16
+ "compile-test": "tsc -p test",
17
+ "compile": "npm run compile-src && npm run compile-test",
18
+ "build": "npm run clean && npm run compile",
19
+ "eslint": "eslint lib test",
20
+ "lint-md": "remark -u preset-lint-recommended .",
21
+ "lint": "npm run lint-md && npm run eslint",
22
+ "fix": "eslint lib test --ext .ts --ignore-pattern *.d.ts --fix",
23
+ "test": "mocha",
24
+ "test-coverage": "c8 npm run test",
25
+ "send-codacy": "c8 report --reporter=text-lcov | codacy-coverage",
26
+ "start": "npm run compile && npm run lint && npm run cover-test"
27
+ },
28
+ "engines": {
29
+ "node": ">=16"
30
+ },
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/Borewit/strtok3.git"
34
+ },
35
+ "license": "MIT",
36
+ "type": "module",
37
+ "exports": {
38
+ ".": {
39
+ "node": "./lib/index.js",
40
+ "default": "./lib/core.js"
41
+ },
42
+ "./core": "./lib/core.js"
43
+ },
44
+ "types": "lib/index.d.ts",
45
+ "files": [
46
+ "lib/**/*.js",
47
+ "lib/**/*.d.ts"
48
+ ],
49
+ "bugs": {
50
+ "url": "https://github.com/Borewit/strtok3/issues"
51
+ },
52
+ "devDependencies": {
53
+ "@eslint/compat": "^1.1.1",
54
+ "@eslint/eslintrc": "^3.1.0",
55
+ "@eslint/js": "^9.7.0",
56
+ "@types/chai": "^4.3.16",
57
+ "@types/debug": "^4.1.12",
58
+ "@types/mocha": "^10.0.7",
59
+ "@types/node": "^20.14.10",
60
+ "@typescript-eslint/eslint-plugin": "^7.16.1",
61
+ "@typescript-eslint/parser": "^7.16.1",
62
+ "c8": "^10.1.2",
63
+ "chai": "^5.1.1",
64
+ "del-cli": "^5.1.0",
65
+ "eslint": "^9.7.0",
66
+ "eslint-config-prettier": "^9.1.0",
67
+ "eslint-import-resolver-typescript": "^3.6.1",
68
+ "eslint-plugin-import": "^2.29.1",
69
+ "eslint-plugin-jsdoc": "^48.7.0",
70
+ "eslint-plugin-node": "^11.1.0",
71
+ "eslint-plugin-unicorn": "^54.0.0",
72
+ "global": "^4.4.0",
73
+ "mocha": "^10.6.0",
74
+ "remark-cli": "^12.0.1",
75
+ "remark-preset-lint-recommended": "^7.0.0",
76
+ "token-types": "^6.0.0",
77
+ "ts-node": "^10.9.2",
78
+ "typescript": "^5.5.3",
79
+ "uint8array-extras": "^1.3.0"
80
+ },
81
+ "dependencies": {
82
+ "@tokenizer/token": "^0.3.0",
83
+ "peek-readable": "^5.1.3"
84
+ },
85
+ "keywords": [
86
+ "tokenizer",
87
+ "reader",
88
+ "token",
89
+ "async",
90
+ "promise",
91
+ "parser",
92
+ "decoder",
93
+ "binary",
94
+ "endian",
95
+ "uint",
96
+ "stream",
97
+ "streaming"
98
+ ],
99
+ "packageManager": "yarn@4.3.1"
100
+ }
@@ -1,19 +0,0 @@
1
- /**
2
- * Module convert fs functions to promise based functions
3
- */
4
- /// <reference types="node" resolution-mode="require"/>
5
- /// <reference types="node" resolution-mode="require"/>
6
- import fs from 'node:fs';
7
- export interface IReadResult {
8
- bytesRead: number;
9
- buffer: Uint8Array;
10
- }
11
- export declare const pathExists: typeof fs.existsSync;
12
- export declare const createReadStream: typeof fs.createReadStream;
13
- export declare function stat(path: fs.PathLike): Promise<fs.Stats>;
14
- export declare function close(fd: number): Promise<void>;
15
- export declare function open(path: fs.PathLike, mode: fs.Mode): Promise<number>;
16
- export declare function read(fd: number, buffer: Uint8Array, offset: number, length: number, position: number): Promise<IReadResult>;
17
- export declare function writeFile(path: fs.PathLike, data: Buffer | string): Promise<void>;
18
- export declare function writeFileSync(path: fs.PathLike, data: Buffer | string): void;
19
- export declare function readFile(path: fs.PathLike): Promise<Buffer>;
package/lib/FsPromise.js DELETED
@@ -1,69 +0,0 @@
1
- /**
2
- * Module convert fs functions to promise based functions
3
- */
4
- import fs from 'node:fs';
5
- export const pathExists = fs.existsSync;
6
- export const createReadStream = fs.createReadStream;
7
- export async function stat(path) {
8
- return new Promise((resolve, reject) => {
9
- fs.stat(path, (err, stats) => {
10
- if (err)
11
- reject(err);
12
- else
13
- resolve(stats);
14
- });
15
- });
16
- }
17
- export async function close(fd) {
18
- return new Promise((resolve, reject) => {
19
- fs.close(fd, err => {
20
- if (err)
21
- reject(err);
22
- else
23
- resolve();
24
- });
25
- });
26
- }
27
- export async function open(path, mode) {
28
- return new Promise((resolve, reject) => {
29
- fs.open(path, mode, (err, fd) => {
30
- if (err)
31
- reject(err);
32
- else
33
- resolve(fd);
34
- });
35
- });
36
- }
37
- export async function read(fd, buffer, offset, length, position) {
38
- return new Promise((resolve, reject) => {
39
- fs.read(fd, buffer, offset, length, position, (err, bytesRead, _buffer) => {
40
- if (err)
41
- reject(err);
42
- else
43
- resolve({ bytesRead, buffer: _buffer });
44
- });
45
- });
46
- }
47
- export async function writeFile(path, data) {
48
- return new Promise((resolve, reject) => {
49
- fs.writeFile(path, data, err => {
50
- if (err)
51
- reject(err);
52
- else
53
- resolve();
54
- });
55
- });
56
- }
57
- export function writeFileSync(path, data) {
58
- fs.writeFileSync(path, data);
59
- }
60
- export async function readFile(path) {
61
- return new Promise((resolve, reject) => {
62
- fs.readFile(path, (err, buffer) => {
63
- if (err)
64
- reject(err);
65
- else
66
- resolve(buffer);
67
- });
68
- });
69
- }