Skip to content

Commit

Permalink
browser: use TextDecoder and TextEncoder for buffer
Browse files Browse the repository at this point in the history
Doing a profiling in chrome dev tools shows that the `Buffer.toString()` and `Buffer.from(string)` is using unexpected long cpu time. With the native TextDecoder and TextEncoder it can get much faster in browsers supporting it.
On browsers not supporting TextDecoder, like Internet Explorer, `Buffer.toString()` and `Buffer.from(string)` would not be changed.

References:
feross/buffer#268
feross/buffer#60
https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder
https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder
  • Loading branch information
myfreeer committed Sep 12, 2020
1 parent 65ea2e4 commit 5cd3516
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/exceljs.bare.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
// this bundle is built without polyfill leaving apps the freedom to add their own
require('./utils/browser-patch-buffer');

const ExcelJS = {
Workbook: require('./doc/workbook'),
};
Expand Down
1 change: 1 addition & 0 deletions lib/exceljs.browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ require('core-js/modules/es.object.keys');
require('core-js/modules/es.symbol');
require('core-js/modules/es.symbol.async-iterator');
require('regenerator-runtime/runtime');
require('./utils/browser-patch-buffer');

const ExcelJS = {
Workbook: require('./doc/workbook'),
Expand Down
34 changes: 34 additions & 0 deletions lib/utils/browser-patch-buffer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/* eslint-disable node/no-unsupported-features/node-builtins */
// Note: this is included only in browser
if (typeof TextDecoder !== 'undefined' || typeof TextEncoder !== 'undefined') {
const {Buffer} = require('buffer');
if (typeof TextEncoder !== 'undefined') {
const textEncoder = new TextEncoder('utf-8');
const {from} = Buffer;
Buffer.from = function(str, encoding) {
if (typeof str === 'string') {
if (encoding) {
encoding = encoding.toLowerCase();
}
if (!encoding || encoding === 'utf8' || encoding === 'utf-8') {
return from.call(this, textEncoder.encode(str).buffer);
}
}
return from.apply(this, arguments);
};
}
if (typeof TextDecoder !== 'undefined') {
const textDecoder = new TextDecoder('utf-8');
const {toString} = Buffer.prototype;
Buffer.prototype.toString = function(encoding, start, end) {
if (encoding) {
encoding = encoding.toLowerCase();
}
if (!start && end === undefined &&
(!encoding || encoding === 'utf8' || encoding === 'utf-8')) {
return textDecoder.decode(this);
}
return toString.apply(this, arguments);
};
}
}

0 comments on commit 5cd3516

Please sign in to comment.