在Node.js中指定base64解码/编码的“备用字符”

0 投票
1 回答
1016 浏览
提问于 2025-04-17 21:01

我正在尝试把一些代码从Python移植到Node.js。代码如下:

//returns the UID contained in the var uid decoded to an int:
uid = 'ABCDE'
struct.unpack(">I", base64.b64decode(uid + 'A==', "[]"))[0] / 4

//encodes the UID int in uidint into the B64 UID:
uidint = 270532
base64.b64encode(struct.pack(">I", uidint * 4), "[]")[0:5]

我已经找到一个库,可以替代Python中struct类的打包和解包功能。

不过,Python的base64实现支持使用替代字符,而Node.js的实现则不支持。

这是我正在进行中的移植工作:

uid = 'ABCDE';
decoded = new Buffer(uid+'A==', 'base64').toString('ascii');
console.log(decoded);
test = jspack.Unpack(">I",decoded)[0] / 4;
console.log(test);

目前,第一个console.log输出了一些奇怪的字符,第二个输出了NaN(不是一个数字)。这也能理解为什么会这样。

我在想有没有人知道怎么复制Python中这种模式的实现。我在npm上查找了很多库,但没有找到任何可能支持这个功能的东西。

1 个回答

1

在创建缓冲区之前,先手动替换它们:

new Buffer(
  (uid+'A==')
    .replace(/\+/g, '[')
    .replace(/\//g, ']')
, 'base64').toString('ascii')

撰写回答