### Install buffer Module via npm Source: https://github.com/feross/buffer/blob/master/README.md This command installs the 'buffer' module using npm. This is the standard method for adding the module to your project's dependencies when not using a bundler like browserify. ```bash npm install buffer ``` -------------------------------- ### Buffer Static Utility Methods - JavaScript Source: https://context7.com/feross/buffer/llms.txt Demonstrates the usage of static Buffer methods for type checking, encoding validation, and calculating byte lengths. Includes examples for Buffer.isBuffer(), Buffer.isEncoding(), and Buffer.byteLength() with various data types and encodings. ```javascript const { Buffer } = require('buffer/') // Check if value is a Buffer console.log(Buffer.isBuffer(Buffer.from('test'))) // true console.log(Buffer.isBuffer(new Uint8Array(10))) // false console.log(Buffer.isBuffer('string')) // false console.log(Buffer.isBuffer(null)) // false console.log(Buffer.isBuffer(undefined)) // false // Validate encoding console.log(Buffer.isEncoding('utf8')) // true console.log(Buffer.isEncoding('hex')) // true console.log(Buffer.isEncoding('base64')) // true console.log(Buffer.isEncoding('ascii')) // true console.log(Buffer.isEncoding('binary')) // true console.log(Buffer.isEncoding('ucs2')) // true console.log(Buffer.isEncoding('utf-8')) // true console.log(Buffer.isEncoding('invalid')) // false // Calculate byte length of string in specific encoding console.log(Buffer.byteLength('Hello', 'utf8')) // 5 console.log(Buffer.byteLength('Hello', 'utf16le')) // 10 console.log(Buffer.byteLength('48656c6c6f', 'hex')) // 5 console.log(Buffer.byteLength('SGVsbG8=', 'base64')) // 5 // Unicode and multi-byte characters console.log(Buffer.byteLength('🚀', 'utf8')) // 4 console.log(Buffer.byteLength('你好', 'utf8')) // 6 console.log('你好'.length) // 2 (character length) // Safe encoding check before use function safeEncode(str, encoding) { if (!Buffer.isEncoding(encoding)) { throw new Error(`Invalid encoding: ${encoding}`) } return Buffer.from(str, encoding) } try { const buf = safeEncode('Hello', 'utf8') console.log(buf.toString()) // 'Hello' safeEncode('test', 'invalid-encoding') // throws } catch (err) { console.log(err.message) // 'Invalid encoding: invalid-encoding' } ``` -------------------------------- ### Buffer Allocation with Buffer.alloc() and Buffer.allocUnsafe() in JavaScript Source: https://context7.com/feross/buffer/llms.txt Allocates new Buffer instances. `Buffer.alloc()` initializes memory to zeros, while `Buffer.allocUnsafe()` leaves memory uninitialized for performance benefits. Both support specifying a fill value and encoding. ```javascript const { Buffer } = require('buffer/') // Allocate zero-filled buffer const buf1 = Buffer.alloc(10) console.log(buf1) // // Allocate and fill with specific value const buf2 = Buffer.alloc(10, 'a') console.log(buf2.toString()) // 'aaaaaaaaaa' // Allocate with fill value and encoding const buf3 = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64') console.log(buf3.toString()) // 'hello world' // Allocate uninitialized buffer (faster but contains random data) const buf4 = Buffer.allocUnsafe(10) // buf4 contains random/garbage data - must fill before use buf4.fill(0) console.log(buf4) // // Performance use case: allocate and immediately write const buf5 = Buffer.allocUnsafe(5) buf5.write('hello') console.log(buf5.toString()) // 'hello' ``` -------------------------------- ### Buffer Creation with Buffer.from() in JavaScript Source: https://context7.com/feross/buffer/llms.txt Creates new Buffer instances from strings (UTF-8, hex, base64), arrays of bytes, ArrayBuffers, and existing Buffers. It supports optional encoding specification for string inputs and copies data from other Buffers. ```javascript const { Buffer } = require('buffer/') // Create buffer from UTF-8 string const buf1 = Buffer.from('Hello World', 'utf8') console.log(buf1) // // Create buffer from hex string const buf2 = Buffer.from('48656c6c6f', 'hex') console.log(buf2.toString()) // 'Hello' // Create buffer from base64 string const buf3 = Buffer.from('SGVsbG8gV29ybGQ=', 'base64') console.log(buf3.toString()) // 'Hello World' // Create buffer from array of bytes const buf4 = Buffer.from([72, 101, 108, 108, 111]) console.log(buf4.toString()) // 'Hello' // Create buffer from ArrayBuffer const arrayBuffer = new ArrayBuffer(8) const buf5 = Buffer.from(arrayBuffer) console.log(buf5.length) // 8 // Copy existing buffer const original = Buffer.from('test') const copy = Buffer.from(original) console.log(copy.toString()) // 'test' ``` -------------------------------- ### Buffer Filling with fill() in Node.js Source: https://context7.com/feross/buffer/llms.txt The `fill()` method populates a Buffer with a specified value. It supports filling with byte values, strings (with optional encoding), and can be restricted to a range within the buffer using offset and end parameters. It can also be used to reset a buffer to zeros. ```javascript const { Buffer } = require('buffer/') // Fill with byte value const buf1 = Buffer.alloc(10) buf1.fill(0x41) // ASCII 'A' console.log(buf1.toString()) // 'AAAAAAAAAA' // Fill with string const buf2 = Buffer.alloc(10) buf2.fill('abc') console.log(buf2.toString()) // 'abcabcabca' // Fill with offset and end const buf3 = Buffer.alloc(10) buf3.fill('x', 2, 8) console.log(buf3.toString()) // '\x00\x00xxxxxx\x00\x00' // Fill with encoding const buf4 = Buffer.alloc(10) buf4.fill('aGVsbG8=', 'base64') console.log(buf4.toString()) // 'helloaGVsbG8=' // Fill entire buffer after offset const buf5 = Buffer.alloc(10).fill('z', 5) console.log(buf5.toString()) // '\x00\x00\x00\x00\x00zzzzz' // Reset buffer (fill with zeros) const buf6 = Buffer.from('sensitive data') buf6.fill(0) console.log(buf6) // // Pattern filling const buf7 = Buffer.alloc(20) buf7.fill('1234') console.log(buf7.toString()) // '12341234123412341234' ``` -------------------------------- ### Convert Buffer to ArrayBuffer in JavaScript Source: https://github.com/feross/buffer/blob/master/README.md This snippet demonstrates converting a Buffer back to an ArrayBuffer using the `.buffer` property and `.slice()` method. An alternative is to use the `to-arraybuffer` npm module. ```javascript var arrayBuffer = buffer.buffer.slice( buffer.byteOffset, buffer.byteOffset + buffer.byteLength ) ``` -------------------------------- ### Buffer Comparison with compare() and equals() in Node.js Source: https://context7.com/feross/buffer/llms.txt Compares buffers lexicographically for sorting and equality checking. Supports static and instance methods for comparison, and the equals() method for exact matches. ```javascript const { Buffer } = require('buffer/') // Compare two buffers const buf1 = Buffer.from('ABC') const buf2 = Buffer.from('ABD') const buf3 = Buffer.from('ABC') console.log(buf1.compare(buf2)) // -1 (buf1 < buf2) console.log(buf2.compare(buf1)) // 1 (buf2 > buf1) console.log(buf1.compare(buf3)) // 0 (buf1 === buf3) // Static compare method console.log(Buffer.compare(buf1, buf2)) // -1 console.log(Buffer.compare(buf2, buf1)) // 1 // Equality check console.log(buf1.equals(buf2)) // false console.log(buf1.equals(buf3)) // true // Compare with offset ranges const buf4 = Buffer.from('ABCDEF') const buf5 = Buffer.from('CDE') console.log(buf4.compare(buf5, 0, 3, 2, 5)) // 0 (comparing 'CDE' with 'CDE') // Sort array of buffers const buffers = [ Buffer.from('banana'), Buffer.from('apple'), Buffer.from('cherry'), Buffer.from('apple') ] buffers.sort(Buffer.compare) console.log(buffers.map(b => b.toString())) // ['apple', 'apple', 'banana', 'cherry'] // Find duplicates using equals const unique = buffers.filter((buf, index) => { return buffers.findIndex(b => b.equals(buf)) === index }) console.log(unique.map(b => b.toString())) // ['apple', 'banana', 'cherry'] ``` -------------------------------- ### Buffer Slicing and Copying with slice() and copy() in Node.js Source: https://context7.com/feross/buffer/llms.txt Extracts portions of a Buffer using slice() which creates a view (shares memory), or copies data between buffers with offset control using copy() for independent copies. ```javascript const { Buffer } = require('buffer/') // Slice buffer (creates view, shares memory) const original = Buffer.from('Hello World') const slice1 = original.slice(0, 5) const slice2 = original.slice(6) console.log(slice1.toString()) // 'Hello' console.log(slice2.toString()) // 'World' // Slice with negative indices const slice3 = original.slice(-5) console.log(slice3.toString()) // 'World' // Note: modifying slice modifies original slice1[0] = 0x4A // 'J' console.log(original.toString()) // 'Jello World' // Copy buffer (creates independent copy) const source = Buffer.from('Copy me') const target = Buffer.alloc(20) const bytesCopied = source.copy(target, 0) console.log(bytesCopied) // 7 console.log(target.toString('utf8', 0, bytesCopied)) // 'Copy me' // Copy with offset and range const src = Buffer.from('0123456789') const dest = Buffer.alloc(10) src.copy(dest, 0, 2, 5) // Copy '234' to start console.log(dest.toString('utf8', 0, 3)) // '234' src.copy(dest, 3, 7, 10) // Copy '789' after '234' console.log(dest.toString('utf8', 0, 6)) // '234789' // Safe copying with bounds checking const small = Buffer.from('tiny') const large = Buffer.alloc(2) const copied = small.copy(large, 0) console.log(copied) // 2 (only copied what fits) console.log(large.toString()) // 'ti' ``` -------------------------------- ### Buffer Searching with indexOf(), lastIndexOf(), and includes() in Node.js Source: https://context7.com/feross/buffer/llms.txt Searches for values within a Buffer, supporting strings, numbers (byte values), and other Buffers. Includes methods for finding the first, last, or checking for the existence of a value. ```javascript const { Buffer } = require('buffer/') // Search for string const buf = Buffer.from('Hello World, Hello Universe') console.log(buf.indexOf('Hello')) // 0 console.log(buf.indexOf('Hello', 1)) // 13 console.log(buf.lastIndexOf('Hello')) // 13 console.log(buf.indexOf('Goodbye')) // -1 // Search for byte value const byteBuf = Buffer.from([1, 2, 3, 4, 5, 3, 2, 1]) console.log(byteBuf.indexOf(3)) // 2 console.log(byteBuf.lastIndexOf(3)) // 5 console.log(byteBuf.indexOf(10)) // -1 // Search for buffer const haystack = Buffer.from('the quick brown fox') const needle = Buffer.from('quick') console.log(haystack.indexOf(needle)) // 4 // Check if value exists console.log(buf.includes('World')) // true console.log(buf.includes('Mars')) // false console.log(byteBuf.includes(3)) // true // Search with encoding const hexBuf = Buffer.from('48656c6c6f', 'hex') console.log(hexBuf.indexOf('6c', 0, 'hex')) // 2 // Find all occurrences const text = Buffer.from('ababababab') const pattern = Buffer.from('ab') const positions = [] let pos = -1 while ((pos = text.indexOf(pattern, pos + 1)) !== -1) { positions.push(pos) } console.log(positions) // [0, 2, 4, 6, 8] ``` -------------------------------- ### Node.js Buffer Byte Order Swapping (swap16, swap32, swap64) Source: https://context7.com/feross/buffer/llms.txt The `swap16()`, `swap32()`, and `swap64()` methods perform in-place byte order swapping on Buffer instances, essential for handling different endianness conventions between systems. These methods require the buffer's length to be a multiple of the swapped bit size (2, 4, or 8 bytes respectively). ```javascript const { Buffer } = require('buffer/') // Swap 16-bit values const buf16 = Buffer.from([0x01, 0x02, 0x03, 0x04]) console.log(buf16.toString('hex')) // '01020304' buf16.swap16() console.log(buf16.toString('hex')) // '02010403' // Swap 32-bit values const buf32 = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]) console.log(buf32.toString('hex')) // '0102030405060708' buf32.swap32() console.log(buf32.toString('hex')) // '0403020108070605' // Swap 64-bit values const buf64 = Buffer.from([ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10 ]) console.log(buf64.toString('hex')) // '0102030405060708090a0b0c0d0e0f10' buf64.swap64() console.log(buf64.toString('hex')) // '08070605040302010100f0e0d0c0b0a09' // Endianness conversion use case const value = 0x12345678 const leBuf = Buffer.alloc(4) leBuf.writeUInt32LE(value) console.log(leBuf.toString('hex')) // '78563412' // Convert to big-endian leBuf.swap32() console.log(leBuf.toString('hex')) // '12345678' console.log(leBuf.readUInt32BE(0)) // 305419896 // Error handling: buffer size must be multiple of swap size try { const invalid = Buffer.alloc(3) invalid.swap16() // Throws RangeError } catch (err) { console.log(err.message) // 'Buffer size must be a multiple of 16-bits' } ``` -------------------------------- ### Convert Buffer to Blob in JavaScript Source: https://github.com/feross/buffer/blob/master/README.md This JavaScript code shows how to convert a Buffer object into a Blob object. It utilizes the Blob constructor, optionally allowing for the specification of a MIME type. ```javascript var blob = new Blob([ buffer ]) ``` ```javascript var blob = new Blob([ buffer ], { type: 'text/html' }) ``` -------------------------------- ### String Encoding/Decoding with toString() and write() in JavaScript Source: https://context7.com/feross/buffer/llms.txt Converts between Buffer and string representations using various encodings (utf8, ascii, hex, base64, binary). `toString()` decodes a buffer to a string, supporting offset and length arguments. `write()` writes a string to a buffer, returning the number of bytes written. ```javascript const { Buffer } = require('buffer/') // Decode buffer to string with various encodings const buf = Buffer.from('Hello World') console.log(buf.toString('utf8')) // 'Hello World' console.log(buf.toString('hex')) // '48656c6c6f20576f726c64' console.log(buf.toString('base64')) // 'SGVsbG8gV29ybGQ=' console.log(buf.toString('ascii')) // 'Hello World' // Decode partial buffer console.log(buf.toString('utf8', 0, 5)) // 'Hello' console.log(buf.toString('utf8', 6)) // 'World' // Write string to buffer const writeBuf = Buffer.alloc(20) let written = writeBuf.write('Hello', 0, 'utf8') console.log(written) // 5 (bytes written) written += writeBuf.write(' World', written, 'utf8') console.log(writeBuf.toString('utf8', 0, written)) // 'Hello World' // Write with different encodings const hexBuf = Buffer.alloc(10) hexBuf.write('48656c6c6f', 0, 'hex') console.log(hexBuf.toString('utf8', 0, 5)) // 'Hello' // Handle encoding errors gracefully const base64Buf = Buffer.alloc(20) const len = base64Buf.write('SGVsbG8=', 'base64') console.log(base64Buf.toString('utf8', 0, len)) // 'Hello' ``` -------------------------------- ### Require buffer Module Explicitly in JavaScript Source: https://github.com/feross/buffer/blob/master/README.md This JavaScript code snippet demonstrates how to explicitly require the 'buffer' module when not using browserify. The trailing slash in 'buffer/' is crucial for differentiating it from the Node.js core module. ```javascript var Buffer = require('buffer/').Buffer // note: the trailing slash is important! ``` -------------------------------- ### Write Numeric Values to Buffer (JavaScript) Source: https://context7.com/feross/buffer/llms.txt Explains how to write signed and unsigned integers, BigInt values, and floating-point numbers into a Node.js Buffer. Supports specifying byte order (little-endian or big-endian). Input is a Buffer and numeric values, output is the modified Buffer. ```javascript const { Buffer } = require('buffer/') // Allocate buffer for numeric data const buf = Buffer.alloc(16) // Write unsigned integers - Little Endian buf.writeUInt8(0x12, 0) buf.writeUInt16LE(0x3456, 1) buf.writeUInt32LE(0x789abcde, 3) console.log(buf.slice(0, 7).toString('hex')) // '125634debc9a78' // Write unsigned integers - Big Endian const beBuf = Buffer.alloc(16) beBuf.writeUInt8(0x12, 0) beBuf.writeUInt16BE(0x3456, 1) beBuf.writeUInt32BE(0x789abcde, 3) console.log(beBuf.slice(0, 7).toString('hex')) // '12345678 9abcde' // Write signed integers const signedBuf = Buffer.alloc(8) signedBuf.writeInt8(-1, 0) signedBuf.writeInt16LE(-257, 1) signedBuf.writeInt32LE(-1, 3) console.log(signedBuf.readInt8(0)) // -1 console.log(signedBuf.readInt16LE(1)) // -257 // Write BigInt values const bigBuf = Buffer.alloc(16) bigBuf.writeBigUInt64LE(0x0102030405060708n, 0) bigBuf.writeBigInt64BE(-1n, 8) console.log(bigBuf.readBigUInt64LE(0)) // 578437695752307201n // Write floating point with proper precision const floatBuf = Buffer.alloc(12) floatBuf.writeFloatLE(3.14159, 0) floatBuf.writeFloatBE(2.71828, 4) floatBuf.writeDoubleLE(1.41421356, 8) console.log(floatBuf.readFloatLE(0).toFixed(5)) // '3.14159' console.log(floatBuf.readFloatBE(4).toFixed(5)) // '2.71828' ``` -------------------------------- ### Read Numeric Values from Buffer (JavaScript) Source: https://context7.com/feross/buffer/llms.txt Demonstrates how to read signed and unsigned integers, BigInt values, and floating-point numbers from a Node.js Buffer. It covers both little-endian and big-endian byte orders. Input is a Buffer object, and output is the numeric value read. ```javascript const { Buffer } = require('buffer/') // Create buffer with numeric data const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0]) // Read unsigned integers - Little Endian console.log(buf.readUInt8(0)) // 18 (0x12) console.log(buf.readUInt16LE(0)) // 13330 (0x3412) console.log(buf.readUInt32LE(0)) // 2018915346 (0x78563412) // Read unsigned integers - Big Endian console.log(buf.readUInt16BE(0)) // 4660 (0x1234) console.log(buf.readUInt32BE(0)) // 305419896 (0x12345678) // Read signed integers const signedBuf = Buffer.from([0xff, 0xfe, 0x80, 0x7f]) console.log(signedBuf.readInt8(0)) // -1 console.log(signedBuf.readInt8(3)) // 127 console.log(signedBuf.readInt16LE(0)) // -257 // Read BigInt values const bigBuf = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]) console.log(bigBuf.readBigUInt64LE(0)) // 578437695752307201n console.log(bigBuf.readBigUInt64BE(0)) // 72623859790382856n // Read floating point const floatBuf = Buffer.alloc(8) floatBuf.writeFloatLE(3.14159, 0) floatBuf.writeDoubleLE(2.718281828, 0) console.log(floatBuf.readFloatLE(0)) // ~3.14159 console.log(floatBuf.readDoubleLE(0)) // ~2.718281828 ``` -------------------------------- ### Convert ArrayBuffer to Buffer in JavaScript Source: https://github.com/feross/buffer/blob/master/README.md This snippet shows how to convert an ArrayBuffer to a Buffer using `Buffer.from()`. This operation is efficient as it does not create a copy of the data. ```javascript var buffer = Buffer.from(arrayBuffer) ``` -------------------------------- ### Concatenate Buffers with Buffer.concat() (JavaScript) Source: https://context7.com/feross/buffer/llms.txt Shows how to combine multiple Node.js Buffer instances into a single Buffer. It supports specifying a total length for the concatenated buffer, which can truncate the result. An empty list of buffers results in an empty buffer. ```javascript const { Buffer } = require('buffer/') // Concatenate multiple buffers const buf1 = Buffer.from('Hello ') const buf2 = Buffer.from('beautiful ') const buf3 = Buffer.from('world!') const combined = Buffer.concat([buf1, buf2, buf3]) console.log(combined.toString()) // 'Hello beautiful world!' console.log(combined.length) // 21 // Concatenate with explicit length const truncated = Buffer.concat([buf1, buf2, buf3], 11) console.log(truncated.toString()) // 'Hello beaut' console.log(truncated.length) // 11 // Concatenate empty list returns empty buffer const empty = Buffer.concat([]) console.log(empty.length) // 0 // Use in streaming data scenarios const chunks = [] chunks.push(Buffer.from('chunk1 ')) chunks.push(Buffer.from('chunk2 ')) chunks.push(Buffer.from('chunk3')) const result = Buffer.concat(chunks) console.log(result.toString()) // 'chunk1 chunk2 chunk3' // Performance optimization: pre-calculate length const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0) const optimized = Buffer.concat(chunks, totalLength) console.log(optimized.toString()) // 'chunk1 chunk2 chunk3' ``` -------------------------------- ### Node.js Buffer JSON Serialization with toJSON() Source: https://context7.com/feross/buffer/llms.txt The `toJSON()` method converts a Buffer instance into a JSON-serializable object representation, typically an object with 'type' set to 'Buffer' and a 'data' array containing the buffer's byte values. This is useful for sending Buffer data over networks or storing it in formats that natively support JSON. ```javascript const { Buffer } = require('buffer/') // Convert buffer to JSON const buf = Buffer.from('Hello') const json = buf.toJSON() console.log(json) // { type: 'Buffer', data: [ 72, 101, 108, 108, 111 ] } console.log(JSON.stringify(json)) // '{"type":"Buffer","data":[72,101,108,108,111]}' // JSON.stringify automatically calls toJSON const directJson = JSON.stringify(buf) console.log(directJson) // '{"type":"Buffer","data":[72,101,108,108,111]}' // Reconstruct buffer from JSON const parsed = JSON.parse(directJson) const reconstructed = Buffer.from(parsed.data) console.log(reconstructed.toString()) // 'Hello' console.log(reconstructed.equals(buf)) // true // Use in API responses const apiResponse = { status: 'success', binaryData: Buffer.from([0x01, 0x02, 0x03]), timestamp: Date.now() } const responseJson = JSON.stringify(apiResponse) console.log(responseJson) // '{"status":"success","binaryData":{"type":"Buffer","data":[1,2,3]},"timestamp":1234567890}' // Restore from API response const restored = JSON.parse(responseJson) const binaryData = Buffer.from(restored.binaryData.data) console.log(binaryData) // ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.