Skip to content

Instantly share code, notes, and snippets.

@lot224
Created December 7, 2022 17:38
Show Gist options
  • Save lot224/99f5bea2f9a525c6607491de859e57f5 to your computer and use it in GitHub Desktop.
Save lot224/99f5bea2f9a525c6607491de859e57f5 to your computer and use it in GitHub Desktop.
Mongo c# driver ObjectId to Guid converter nodejs
const b64ToGuid = (b64) => {
const bytes = Buffer.from(b64, "base64");
bits = [];
bytes.forEach(byte => {
bits.push(byte.toString(16).padStart(2, '0'));
});
const data = bits.join("");
const parts = [];
parts.push(data.substring(0, 8).split("").reverse().join(""));
parts.push(data.substring(8, 12).split("").reverse().join(""));
parts.push(data.substring(12, 16).split("").reverse().join(""));
parts.push(data.substring(16, 20));
parts.push(data.substring(20));
return parts.join("-");
}
const guidToB64 = (guid) => {
const data = guid.replaceAll("-", "");
const parts = [];
parts.push(data.substring(0, 8).split("").reverse().join(""));
parts.push(data.substring(8, 12).split("").reverse().join(""));
parts.push(data.substring(12, 16).split("").reverse().join(""));
parts.push(data.substring(16, 20));
parts.push(data.substring(20));
const bytes = [];
parts.join("").match(/.{1,2}/g).forEach(bit => {
bytes.push(parseInt(bit, 16));
});
const buff = Buffer.from(bytes);
return buff.toString("base64");
}
const b = "MyIRAFVEd2aImaq7zN3u/w==";
const g = b64ToGuid(b);
const b64 = guidToB64(g);
console.log(g);
console.log(b64);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment