📜  Node.js Buffer.swap64() 方法

📅  最后修改于: 2022-05-13 01:56:52.021000             🧑  作者: Mango

Node.js Buffer.swap64() 方法

Buffer.swap64() 方法Buffer模块中 Buffer 类的内置应用程序编程接口,用于就地交换缓冲区字节顺序。通过将缓冲区解释为 64 位数字的数组来执行交换。

句法:

Buffer.swap64()

参数:此方法不接受任何参数。

返回值:它返回对缓冲区的引用。

抛出的错误:如果缓冲区长度 (buf.length) 不是 8 的倍数,则抛出ERR_INVALID_BUFFER_SIZE

下面的例子说明了在 Node.js 中使用Buffer.swap64()方法:

示例 1:

// Node.js program to demonstrate the 
// Buffer.swap64() method 
      
// Creating a buffer 
const buf = Buffer.from([0x7, 0x0, 0x1,
              0x1, 0x4, 0x5, 0x4, 0x6]); 
  
// Display the buffer value
// before swap 
console.log(buf); 
  
// Using Buffer.swap64() method
buf.swap64();
      
// Display the result 
// after swap
console.log(buf); 

输出:



示例 2:我们将查看此方法引发的错误

// Node.js program to demonstrate the 
// Buffer.swap64() method 
      
// Creating a buffer 
const buf = Buffer.from([0x0,
         0x1, 0x2, 0x3, 0x4, 0x5]); 
  
// Display the buffer value
// before swap 
console.log(buf); 
  
try {
    // Using Buffer.swap64() method
    // It will throw error
    buf.swap64();
  
    // Display the result 
    // after swap
    console.log(buf);
}
catch(e) {
    console.log("Entering catch block");
  
    // Display error
    console.log(e);
}

输出:


Entering catch block
RangeError [ERR_INVALID_BUFFER_SIZE]: Buffer size must be a multiple of 64-bits
    at Buffer.swap64 (buffer.js:1059:11)
    at /home/runner/index.js:14:9
    .......

注意:以上程序将使用node index.js命令编译运行。

参考: https://nodejs.org/dist/latest-v13.x/docs/api/buffer.html#buffer_buf_swap64