From 6607dbc18a07d8f5ec1614647b2beb9f84021bcc Mon Sep 17 00:00:00 2001 From: Vitaly Puzrin Date: Sat, 7 Nov 2020 22:57:35 +0300 Subject: [PATCH] Cleanup example --- examples/README.md | 2 +- examples/browser.html | 71 ++++++------------------------------------- examples/server.js | 23 ++++++-------- 3 files changed, 21 insertions(+), 75 deletions(-) diff --git a/examples/README.md b/examples/README.md index 028a215..f2b3c66 100644 --- a/examples/README.md +++ b/examples/README.md @@ -2,5 +2,5 @@ Demo of sending compressed objects from browser to server. Run `node server.js` and open `browser.html`. -__Warning!__ This is the sample only, to explain data reencoding steps. It does +__Warning!__ This is the sample only, to show data reencoding steps. It does not have error checks and so on. Don't copy-paste to production code "as is". diff --git a/examples/browser.html b/examples/browser.html index 8a0b6c7..9ee73ca 100644 --- a/examples/browser.html +++ b/examples/browser.html @@ -5,43 +5,20 @@ diff --git a/examples/server.js b/examples/server.js index 936aede..0872f0c 100644 --- a/examples/server.js +++ b/examples/server.js @@ -1,12 +1,15 @@ 'use strict'; -/*eslint-disable no-console*/ +/* eslint-disable no-console */ const http = require('http'); -const pako = require('../'); const multiparty = require('multiparty'); const fs = require('fs'); +const zlib = require('zlib'); +const util = require('util'); +const readFile = util.promisify(fs.readFile); +const inflate = util.promisify(zlib.inflate); const MULTIPART_RE = /^multipart\/form-data(?:;|$)/i; const MAX_FIELDS_SIZE = 100 * 1024; // 100kb @@ -20,8 +23,7 @@ function error(msg) { } - -const server = http.createServer(async (req, res) => { +const server = http.createServer(async function (req, res) { console.log('--- received request'); @@ -60,22 +62,17 @@ const server = http.createServer(async (req, res) => { throw err; } - // In ideal world, we should process data as stream to minimize memory use - // on big data (and use node's `zlib` inflate). - // - // But that's just a quick sample to explain data reencoding steps from - // browser to server. Feel free to improve. - let bin = fs.readFileSync(files.binson[0].path); + let bin = await readFile(files.binson[0].path); // Kludge - here we should cleanup all files fs.unlinkSync(files.binson[0].path); // Decompress binary content // Note! Can throw error on bad data - let uncompressed = pako.inflate(new Uint8Array(bin), { to: 'string' }); + let uncompressed = await inflate(bin); - // Convert utf8 -> utf16 (native JavaScript string format) - let decoded = decodeURIComponent(escape(uncompressed)); + // Convert utf8 buffer -> utf16 string (native JavaScript string format) + let decoded = uncompressed.toString(); // Finally, create an object // Note! Can throw error on bad data