What is swap64() in Node.js Buffer Module?

The swap64 function in Node.js Buffer Module

The swap64 function is a member function of Buffer class in the Node.js Buffer Module. The swap64 function is used to swap the byte order in place of a Buffer instance by considering it a 64-bit (or 8 bytes) array. The syntax of the swap64 function is as follows:

buf.swap64()

Parameters

swap64 takes no parameters.

Return value

  • Returns a reference to buf of type Buffer.

Description

The swap64 function reverses every 8-byte group present in the buffer buf by treating the buf as a 64-bit (or 8 bytes) array.

Example usage of the swap64 function

The following code snippet provides an example of how to use the swap64 function:

const b = Buffer.from([0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7]);
console.log("Buffer before swap64:")
console.log(b);
b.swap64();
console.log("Buffer after swap64:")
console.log(b);

In the example above, the first group of 4 bytes (00, 01, 02, 03, 04, 05, 06, 07) is reversed, resulting in the order 07, 06, 05, 04, 03, 02, 01, 00.

If the number of bytes is not enough to form 8-byte groups, then ERR_INVALID_BUFFER_SIZE error is thrown. Below is an example:

const b = Buffer.from([0x0, 0x1, 0x2, 0x3, 0x4, 0x5]);
console.log("Buffer before swap64:")
console.log(b);
b.swap64();
console.log("Buffer after swap64:")
console.log(b);
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved