From 2f9191d0c020c5d74e238bf1e222979490b64026 Mon Sep 17 00:00:00 2001 From: Walle Cyril Date: Tue, 17 Dec 2019 18:09:03 +0100 Subject: [PATCH] use streams API in the multipart example --- example/multipartParser.js | 34 +++++++++++++--------------------- 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/example/multipartParser.js b/example/multipartParser.js index f990a2da..c9ef9117 100644 --- a/example/multipartParser.js +++ b/example/multipartParser.js @@ -1,8 +1,6 @@ const { MultipartParser } = require('../lib/multipart_parser.js'); -const multipartParser = new MultipartParser(); - // hand crafted multipart const boundary = '--abcxyz'; const next = '\r\n'; @@ -11,25 +9,19 @@ const buffer = Buffer.from( `${boundary}${next}${formData}name="text"${next}${next}text ...${next}${next}${boundary}${next}${formData}name="z"${next}${next}text inside z${next}${next}${boundary}${next}${formData}name="file1"; filename="a.txt"${next}Content-Type: text/plain${next}${next}Content of a.txt.${next}${next}${boundary}${next}${formData}name="file2"; filename="a.html"${next}Content-Type: text/html${next}${next}Content of a.html.${next}${next}${boundary}--` ); -const logAnalyzed = (buffer, start, end) => { +const multipartParser = new MultipartParser(); +multipartParser.on('data', ({name, buffer, start, end}) => { + console.log(`${name}:`); if (buffer && start && end) { - console.log(String(buffer.slice(start, end))) + console.log(String(buffer.slice(start, end))); } -}; - -// multipartParser.onPartBegin -// multipartParser.onPartEnd - -// multipartParser.on('partData', logAnalyzed) // non supported syntax -multipartParser.onPartData = logAnalyzed; -multipartParser.onHeaderField = logAnalyzed; -multipartParser.onHeaderValue = logAnalyzed; -multipartParser.initWithBoundary(boundary.substring(2)); - - -const bytesParsed = multipartParser.write(buffer); -const error = multipartParser.end(); - -if (error) { + console.log(); +}); +multipartParser.on('error', (error) => { console.error(error); -} +}); + +multipartParser.initWithBoundary(boundary.substring(2)); // todo make better error message when it is forgotten +const shouldWait = !multipartParser.write(buffer); +multipartParser.end(); +// multipartParser.destroy();