-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
examples.ts
51 lines (42 loc) · 1.84 KB
/
examples.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { assert } from 'chai';
import * as fs from 'node:fs';
import { EndOfStreamError, StreamReader } from '../lib/index.js';
describe('Examples', () => {
it('first example', async () => {
const readable = fs.createReadStream(new URL('resources/JPEG_example_JPG_RIP_001.jpg', import.meta.url));
const streamReader = new StreamReader(readable);
const uint8Array = new Uint8Array(16);
const bytesRead = await streamReader.read(uint8Array, 0, 16);
assert.equal(bytesRead, 16);
});
it('End-of-stream detection', async () => {
const fileReadStream = fs.createReadStream(new URL('resources/JPEG_example_JPG_RIP_001.jpg', import.meta.url));
const streamReader = new StreamReader(fileReadStream);
const uint8Array = new Uint8Array(16);
assert.equal(await streamReader.read(uint8Array, 0, 16), 16);
try {
while(await streamReader.read(uint8Array, 0, 1) > 0);
assert.fail('Should throw EndOfStreamError');
} catch(error) {
assert.isOk(error instanceof EndOfStreamError, 'Expect `error` to be instance of `EndOfStreamError`');
console.log('End-of-stream reached');
}
});
it('peek', async () => {
const fileReadStream = fs.createReadStream(new URL('resources/JPEG_example_JPG_RIP_001.jpg', import.meta.url));
const streamReader = new StreamReader(fileReadStream);
const buffer = new Uint8Array(20);
let bytesRead = await streamReader.peek(buffer, 0, 3);
if (bytesRead === 3 && buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[2] === 0xFF) {
console.log('This is a JPEG file');
} else {
throw new Error('Expected a JPEG file');
}
bytesRead = await streamReader.read(buffer, 0, 20); // Read JPEG header
if (bytesRead === 20) {
console.log('Got the JPEG header');
} else {
throw new Error('Failed to read JPEG header');
}
});
});