| 1 | import { Dicer } from "../lib/main"; |
| 2 | import * as fs from "fs"; |
| 3 | import * as stream from "stream"; |
| 4 | |
| 5 | function testDicerSyntax() { |
| 6 | const opts: Dicer.Config = { |
| 7 | boundary: "testing", |
| 8 | }; |
| 9 | const dicer = new Dicer(opts); |
| 10 | const opts2: Dicer.Config = { |
| 11 | headerFirst: true, |
| 12 | maxHeaderPairs: 1, |
| 13 | }; |
| 14 | const opts3: Dicer.Config = { |
| 15 | boundary: "more-testing", |
| 16 | headerFirst: false, |
| 17 | maxHeaderPairs: 8, |
| 18 | }; |
| 19 | dicer.setBoundary("new-testing-boundary"); |
| 20 | dicer.on("part", handleDicerPartStream); |
| 21 | dicer.on("finish", () => { |
| 22 | console.log("dicer parsing finished"); |
| 23 | }); |
| 24 | dicer.on("preamble", part => { |
| 25 | console.log("dicer preamble to new part"); |
| 26 | }); |
| 27 | dicer.on("trailer", data => { |
| 28 | console.log(`dicer trailing data found: ${data.length} bytes`); |
| 29 | }); |
| 30 | dicer.on("close", () => { |
| 31 | console.log("dicer close"); |
| 32 | }); |
| 33 | dicer.on("drain", () => { |
| 34 | console.log("dicer drain"); |
| 35 | }); |
| 36 | dicer.on("error", err => { |
| 37 | console.error(`dicer error: ${err.message || JSON.stringify(err)}`); |
| 38 | }); |
| 39 | dicer.on("finish", () => { |
| 40 | console.log("dicer finish"); |
| 41 | }); |
| 42 | dicer.on("pipe", (src: stream.Readable) => { |
| 43 | console.log("dicer pipe"); |
| 44 | }); |
| 45 | dicer.on("unpipe", (src: stream.Readable) => { |
| 46 | console.log("dicer unpipe"); |
| 47 | }); |
| 48 | const inputFileStream = fs.createReadStream("in-test-file.txt"); |
| 49 | inputFileStream.pipe(dicer); |
| 50 | } |
| 51 | /** |
| 52 | * Handle a part found by a Dicer parser |
| 53 | * |
| 54 | * @param part Part found |
| 55 | */ |
| 56 | function handleDicerPartStream(part: Dicer.PartStream) { |
| 57 | console.log("dicer part found"); |
| 58 | const outputFileStream = fs.createWriteStream("out-test-file.txt"); |
| 59 | part.on("readable", () => { |
| 60 | console.log("part readable"); |
| 61 | }); |
| 62 | part.on("header", header => { |
| 63 | console.log(`part header found:\n${JSON.stringify(header)}`); |
| 64 | }); |
| 65 | part.on("data", () => { |
| 66 | console.log("part data"); |
| 67 | }); |
| 68 | part.on("finish", () => { |
| 69 | console.log("part finished"); |
| 70 | }); |
| 71 | part.on("error", err => { |
| 72 | console.error(`part error: ${err.message || JSON.stringify(err)}`); |
| 73 | }); |
| 74 | part.on("end", () => { |
| 75 | console.log("part ended"); |
| 76 | }); |
| 77 | part.on("close", () => { |
| 78 | console.log("part closed"); |
| 79 | }); |
| 80 | part.pipe(outputFileStream); |
| 81 | } |