2014-03-06 38 views
0

我想將一些代碼從python移植到節點。代碼如下:在node.js中的base64解碼/編碼中指定'替代字符'

//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的結構類提供的pack/unpacking功能。

但是,base64的python的implementation支持允許替代字符。不幸的是,節點沒有。

這是我的工作正在進行端口:

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

創建緩衝區之前手動只需更換其中:

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

哇,這從未發生過我。我想這就是那些「很明顯你沒有想到它」中的一個,但是,它在解壓時仍然吐出相同的NaN。所以也許問題是與jspack.Unpack。實際上我不太確定它是如何在python中工作的,或者它是用來完成的,我只是試圖將它移植到我正在使用的IRCd項目中(P10 userid numerics)。我現在處於虧損狀態。我猜如果這是jspack的問題,它與這個base64問題無關。 – WhiskeyTangoFoxtrot