bufferutil is what makes ws fast. It provides some utilities to efficiently
perform some operations such as masking and unmasking the data payload of
WebSocket frames.
npm install bufferutil --save-optional
The --save-optional flag tells npm to save the package in your package.json
under the optionalDependencies
key.
The module exports 3 different functions.
Merges an array of buffers into a target buffer.
target- The target buffer.list- An array containing theBufferinstances to merge.
'use strict';
const bufferUtil = require('bufferutil');
const crypto = require('crypto');
const target = Buffer.allocUnsafe(10);
bufferUtil.merge(target, [crypto.randomBytes(5), crypto.randomBytes(5)]);Masks a buffer using the given masking-key as specified by the WebSocket protocol.
source- The buffer to mask.mask- A buffer representing the masking-key.output- The buffer where to store the result.offset- The offset at which to start writing.length- The number of bytes to mask.
'use strict';
const bufferUtil = require('bufferutil');
const crypto = require('crypto');
const source = crypto.randomBytes(10);
const mask = crypto.randomBytes(4);
bufferUtil.mask(source, mask, source, 0, source.length);Unmasks a buffer using the given masking-key as specified by the WebSocket protocol.
buffer- The buffer to unmask.mask- A buffer representing the masking-key.
'use strict';
const bufferUtil = require('bufferutil');
const crypto = require('crypto');
const buffer = crypto.randomBytes(10);
const mask = crypto.randomBytes(4);
bufferUtil.unmask(buffer, mask);