Node.js缓冲区字符串序列化

6
我希望能够将缓冲区序列化为字符串,而不会增加任何开销(一个字符对应一个字节),并且能够将其反序列化回缓冲区。
var b = new Buffer (4) ;
var s = b.toString() ;
var b2 = new Buffer (s) 

只有在小于128的值下才能产生相同的结果。我想使用0-255的整个范围。

我知道我可以使用循环和String.fromCharCode()在序列化中,以及String.charCodeAt()在反序列化中进行编写,但如果有任何本地模块实现,我正在寻找它。


2
有一个已弃用的“binary”编码。但我建议使用“base64”编码。 - Alexey Ten
@AlexeyTen 这就是正确的答案! - FelikZ
1个回答

9
您可以使用"latin1"编码,但通常应尽量避免使用它,因为将缓冲区转换为二进制字符串会增加一些额外的计算开销。
示例:
var b = Buffer.alloc(4);
var s = b.toString('latin1');
var b2 = Buffer.from(s, 'latin1');

答案似乎已经过时了。node.js打印DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead. new Buffer(s, 'binary') 应该被替换为 Buffer.from(s, 'binary')。https://nodejs.org/en/docs/guides/buffer-constructor-deprecation/#variant-1:~:text=What%20you%20would%20do%20in%20this%20case%20is - shitpoet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接