### Install bufferutil Source: https://github.com/websockets/bufferutil/blob/master/README.md Install bufferutil as an optional dependency. This ensures it's included in your project but won't prevent installation if it fails. ```bash npm install bufferutil --save-optional ``` -------------------------------- ### Install BufferUtil as Optional Dependency Source: https://context7.com/websockets/bufferutil/llms.txt This bash command installs bufferutil as an optional dependency, allowing applications to continue functioning even if native compilation fails. This is the recommended setup for WebSocket libraries. ```bash # Install as an optional dependency (recommended) npm install bufferutil --save-optional ``` -------------------------------- ### Package.json Configuration for Optional Dependency Source: https://context7.com/websockets/bufferutil/llms.txt This JSON snippet shows how to declare bufferutil as an optional dependency in package.json. This ensures that installation failures for bufferutil are non-fatal. ```json // package.json — declare as optional so install failures are non-fatal { "name": "my-websocket-server", "dependencies": { "ws": "^8.0.0" }, "optionalDependencies": { "bufferutil": "^4.0.0" } } ``` -------------------------------- ### WebSocket Server with Automatic BufferUtil Integration Source: https://context7.com/websockets/bufferutil/llms.txt This JavaScript code demonstrates a basic WebSocket server using the 'ws' library. 'bufferutil' is used transparently by 'ws' for accelerating frame masking and unmasking, requiring no explicit integration in application code. ```javascript 'use strict'; // ws automatically uses bufferutil when available; // no explicit require needed in application code. const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { ws.on('message', (data) => { // bufferutil's mask/unmask was used transparently by ws // to decode this incoming frame. console.log('Received:', data.toString()); ws.send('Echo: ' + data); // bufferutil masks the outgoing frame }); }); console.log('WebSocket server running on ws://localhost:8080'); // bufferutil accelerates all frame masking/unmasking automatically. ``` -------------------------------- ### Test BufferUtil Native vs. Fallback Source: https://context7.com/websockets/bufferutil/llms.txt This code tests the native bufferutil addon against its pure JavaScript fallback to ensure byte-for-byte identical output for mask operations. It requires both the native and fallback implementations to be available. ```javascript 'use strict'; // Automatic fallback — no code change needed; index.js handles it transparently: // try { module.exports = require('node-gyp-build')(__dirname); } // catch (e) { module.exports = require('./fallback'); } const bufferUtil = require('bufferutil'); // always works // If you need to explicitly use the pure-JS version (e.g., in tests): const fallback = require('bufferutil/fallback'); const native = require('node-gyp-build')(require('path').join(__dirname, 'node_modules/bufferutil')); const crypto = require('crypto'); const assert = require('assert'); const sizes = [1, 127, 128, 200, 1024, 10 * 1024]; const offsets = [0, 1, 10, 16, 128]; for (const size of sizes) { for (const offset of offsets) { const src = crypto.randomBytes(size); const mask = crypto.randomBytes(4); const destNative = crypto.randomBytes(size + offset); const destFallback = Buffer.from(destNative); native.mask(src, mask, destNative, offset, size); fallback.mask(src, mask, destFallback, offset, size); assert.deepStrictEqual(destNative, destFallback, `mask mismatch at size=${size} offset=${offset}`); } } console.log('Native and fallback produce identical output for all sizes and offsets.'); ``` -------------------------------- ### bufferUtil.mask Source: https://context7.com/websockets/bufferutil/llms.txt Applies the WebSocket masking algorithm to a source buffer, writing the result to an output buffer. This function can perform in-place masking if the source and output buffers are the same. It is optimized for performance by operating on 8-byte aligned chunks. ```APIDOC ## bufferUtil.mask(source, mask, output, offset, length) ### Description Masks a buffer with a 4-byte WebSocket masking key. Applies the WebSocket masking algorithm (XOR of each byte with `mask[i % 4]`) to `length` bytes of `source`, writing the result into `output` starting at `offset`. The source and output buffers may be the same buffer (in-place masking). ### Parameters - **source** (Buffer) - The buffer containing the data to mask. - **mask** (Buffer) - The 4-byte masking key. - **output** (Buffer) - The buffer to write the masked data to. - **offset** (number) - The offset in the output buffer where the masked data should be written. - **length** (number) - The number of bytes to mask. ### Request Example ```javascript 'use strict'; const bufferUtil = require('bufferutil'); const crypto = require('crypto'); // --- In-place masking (source === output) --- const payload = Buffer.from('Hello, WebSocket!', 'utf8'); const maskingKey = crypto.randomBytes(4); // Must always be exactly 4 bytes console.log('Original :', payload.toString('hex')); bufferUtil.mask(payload, maskingKey, payload, 0, payload.length); console.log('Masked :', payload.toString('hex')); // --- Masking into a separate output buffer with an offset --- // Useful when building a WebSocket frame where header bytes precede payload. const src = Buffer.from([0x6c, 0x3c, 0x58, 0xd9, 0x3e, 0x21, 0x09, 0x9f]); const key = Buffer.from([0x48, 0x2a, 0xce, 0x24]); const frame = Buffer.alloc(src.length + 2); // 2 header bytes + masked payload bufferUtil.mask(src, key, frame, 2, src.length); // frame[0] and frame[1] remain 0x00 (reserved for frame header fields) // frame[2..9] = [0x24, 0x16, 0x96, 0xfd, 0x76, 0x0b, 0xc7, 0xbb] console.log('Frame with offset:', frame.toString('hex')); // Expected: 000024169 6fd760bc7bb ``` ``` -------------------------------- ### Mask WebSocket Data with bufferutil Source: https://github.com/websockets/bufferutil/blob/master/README.md Masks a source buffer using a provided masking key. Ensure correct buffer sizes and offsets to prevent errors, as parameters are not validated. ```javascript '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); ``` -------------------------------- ### Mask a buffer with a 4-byte WebSocket masking key Source: https://context7.com/websockets/bufferutil/llms.txt Applies the WebSocket masking algorithm to a source buffer, writing the result to an output buffer. The source and output can be the same for in-place masking. Ensure all arguments are correct as no parameter validation is performed. ```javascript 'use strict'; const bufferUtil = require('bufferutil'); const crypto = require('crypto'); // --- In-place masking (source === output) --- const payload = Buffer.from('Hello, WebSocket!', 'utf8'); const maskingKey = crypto.randomBytes(4); // Must always be exactly 4 bytes console.log('Original :', payload.toString('hex')); bufferUtil.mask(payload, maskingKey, payload, 0, payload.length); console.log('Masked :', payload.toString('hex')); // --- Masking into a separate output buffer with an offset --- // Useful when building a WebSocket frame where header bytes precede payload. const src = Buffer.from([0x6c, 0x3c, 0x58, 0xd9, 0x3e, 0x21, 0x09, 0x9f]); const key = Buffer.from([0x48, 0x2a, 0xce, 0x24]); const frame = Buffer.alloc(src.length + 2); // 2 header bytes + masked payload bufferUtil.mask(src, key, frame, 2, src.length); // frame[0] and frame[1] remain 0x00 (reserved for frame header fields) // frame[2..9] = [0x24, 0x16, 0x96, 0xfd, 0x76, 0x0b, 0xc7, 0xbb] console.log('Frame with offset:', frame.toString('hex')); // Expected: 000024169 6fd760bc7bb ``` -------------------------------- ### bufferUtil.unmask Source: https://github.com/websockets/bufferutil/blob/master/README.md Unmasks a buffer using the provided masking-key according to the WebSocket protocol. It is the caller's responsibility to ensure parameters are correct for maximum performance. ```APIDOC ## bufferUtil.unmask(buffer, mask) ### Description Unmasks a buffer using the given masking-key as specified by the WebSocket protocol. ### Arguments - `buffer` - The buffer to unmask. - `mask` - A buffer representing the masking-key. ### Example ```js 'use strict'; const bufferUtil = require('bufferutil'); const crypto = require('crypto'); const buffer = crypto.randomBytes(10); const mask = crypto.randomBytes(4); bufferUtil.unmask(buffer, mask); ``` ``` -------------------------------- ### bufferUtil.mask Source: https://github.com/websockets/bufferutil/blob/master/README.md Masks a buffer using the provided masking-key according to the WebSocket protocol. It is the caller's responsibility to ensure parameters are correct for maximum performance. ```APIDOC ## bufferUtil.mask(source, mask, output, offset, length) ### Description Masks a buffer using the given masking-key as specified by the WebSocket protocol. ### Arguments - `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. ### Example ```js '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); ``` ``` -------------------------------- ### Unmask WebSocket Data with bufferutil Source: https://github.com/websockets/bufferutil/blob/master/README.md Unmasks a buffer using the provided masking key. The function operates in-place on the buffer. Caller is responsible for validating inputs. ```javascript 'use strict'; const bufferUtil = require('bufferutil'); const crypto = require('crypto'); const buffer = crypto.randomBytes(10); const mask = crypto.randomBytes(4); bufferUtil.unmask(buffer, mask); ``` -------------------------------- ### Unmask a buffer in-place with a 4-byte WebSocket masking key Source: https://context7.com/websockets/bufferutil/llms.txt Reverses the WebSocket masking operation by XOR-ing each byte of the buffer with the masking key. This operation modifies the buffer in place. The same algorithm is used for masking and unmasking. ```javascript 'use strict'; const bufferUtil = require('bufferutil'); const crypto = require('crypto'); // Simulate receiving a masked WebSocket frame payload const original = Buffer.from('Hello, WebSocket!', 'utf8'); const maskingKey = crypto.randomBytes(4); // First, mask (as a client would before sending) const masked = Buffer.allocUnsafe(original.length); bufferUtil.mask(original, maskingKey, masked, 0, original.length); console.log('Masked :', masked.toString('hex')); // Then unmask (as a server would upon receiving) bufferUtil.unmask(masked, maskingKey); console.log('Unmasked :', masked.toString('utf8')); // Expected: 'Hello, WebSocket!' // Verify round-trip correctness const assert = require('assert'); assert.deepStrictEqual(masked, original); console.log('Round-trip OK'); // --- Concrete byte-level example from the test suite --- const buf = Buffer.from([0x24, 0x16, 0x96, 0xfd, 0x76, 0x0b, 0xc7, 0xbb]); const key = Buffer.from([0x48, 0x2a, 0xce, 0x24]); bufferUtil.unmask(buf, key); assert.deepStrictEqual(buf, Buffer.from([0x6c, 0x3c, 0x58, 0xd9, 0x3e, 0x21, 0x09, 0x9f])); console.log('Byte-level unmask OK:', buf.toString('hex')); // Expected: 6c3c58d93e21099f ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.