On this page

    M

    http.websocketMask

    History
    http.websocketMask(source, mask, output, offset, length): void
    Attributes
    The data to mask.
    The 4-byte masking key.
    Where to write the masked data.
    offset:integer
    Byte offset in output at which to start writing.
    length:integer
    Number of bytes of source to mask.

    XORs the first length bytes of source with mask, repeated, and writes the result to output starting at offset: byte i of source is XORed with byte i % 4 of mask. This is the masking operation that WebSocket clients apply to every frame payload they send (RFC 6455, Section 5.3), and that servers undo on every frame they receive. Applying it twice with the same mask restores the original data. source is not modified, unless it shares memory with output.

    All arguments are treated as raw bytes, whatever the view type. source and output may be the same view or overlapping views over the same memory; the result is the same as if source had been copied first.

    An error is thrown if mask is not exactly 4 bytes long, if length is greater than source.byteLength, if offset + length is greater than output.byteLength, or if output is backed by an immutable ArrayBuffer. Nothing is written in that case. source and mask may be backed by an immutable ArrayBuffer.

    import { Buffer } from 'node:buffer';
    import { websocketMask, websocketUnmask } from 'node:http';
    
    const key = Buffer.from([0x37, 0xfa, 0x21, 0x3d]);
    const payload = Buffer.from('Hello');
    
    // Write a masked copy of the payload after a 6-byte frame header.
    const frame = Buffer.alloc(6 + payload.length);
    websocketMask(payload, key, frame, 6, payload.length);
    console.log(frame.subarray(6));
    // Prints: <Buffer 7f 9f 4d 51 58>
    
    const received = frame.subarray(6);
    websocketUnmask(received, key);
    console.log(received.toString());
    // Prints: Hello
    const { Buffer } = require('node:buffer');
    const { websocketMask, websocketUnmask } = require('node:http');
    
    const key = Buffer.from([0x37, 0xfa, 0x21, 0x3d]);
    const payload = Buffer.from('Hello');
    
    // Write a masked copy of the payload after a 6-byte frame header.
    const frame = Buffer.alloc(6 + payload.length);
    websocketMask(payload, key, frame, 6, payload.length);
    console.log(frame.subarray(6));
    // Prints: <Buffer 7f 9f 4d 51 58>
    
    const received = frame.subarray(6);
    websocketUnmask(received, key);
    console.log(received.toString());
    // Prints: Hello