Skip to content

Commit

Permalink
use streams API in the multipart example
Browse files Browse the repository at this point in the history
  • Loading branch information
GrosSacASac committed Dec 17, 2019
1 parent daebbde commit 2f9191d
Showing 1 changed file with 13 additions and 21 deletions.
34 changes: 13 additions & 21 deletions example/multipartParser.js
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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}<!DOCTYPE html><title>Content of a.html.</title>${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();

0 comments on commit 2f9191d

Please sign in to comment.