Commit 56b05657 authored by Jonathan Essex's avatar Jonathan Essex 💬

Added block reader api

parent 675a5f60
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
const { BlockWriter } = require('./blockwriter');
class BlockReader {
static of(stream, readBody = a=>a, encoding = "utf-8") {
let reader = stream.getReader();
return {
start(controller) {
const transformer = new BlockWriter((header,body)=>controller.enqueue({header, body: readBody(body)}), encoding);
// The following function handles each data chunk
function pump() {
// "done" is a Boolean and value a "Uint8Array"
reader.read().then(({ done, value }) => {
// Is there no more data to read?
if (done) {
transformer.close();
controller.close();
return;
}
transformer.write(value);
pump();
});
};
pump();
}
};
}
}
module.exports = { BlockReader };
......@@ -37,7 +37,7 @@ function createBodySink(callback, length) {
class BlockWriter {
constructor(callback, encoding, bodyHandler) {
constructor(callback, encoding) {
this.encoding = encoding;
this.callback = callback;
this.sink = createHeaderSink(hdr=>this.receiveHeader(hdr), this.encoding);
......
......@@ -4,8 +4,9 @@
* and open the template in the editor.
*/
const { BlockWriter } = require('./blockwriter')
const { BlockReader } = require('./blockreader')
const { Tokenizer } = require("./tokenizer.js");
const { Parser } = require("./parser.js");
const { Decoder } = require("./decoder.js");
module.exports = { BlockWriter, Decoder, Parser, Tokenizer };
\ No newline at end of file
module.exports = { BlockWriter, Decoder, Parser, Tokenizer, BlockReader };
\ No newline at end of file
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/* global expect */
const { BlockReader } = require("../../index.js");
const { getFile } = require("./utils.js");
const { ReadableStream } = require("web-streams-polyfill/ponyfill");
const Blob = require("cross-blob");
describe("test block with file", () => {
it("reads test file", checksDone => {
let blockStream = new ReadableStream(BlockReader.of(getFile('testfile.jdb')));
let blockReader = blockStream.getReader();
let count = 0;
function processBlock({ done, block }) {
if (done) {
expect(count).toEqual(4);
checksDone();
} else {
count++;
return blockReader.read().then(processBlock);
}
}
return blockReader.read().then(processBlock);
});
});
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment