node.js 如何将“二进制”编码字符串解码为原始二进制缓冲区?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13823722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to decode "binary" encoded string into raw binary Buffer?
提问by Joshua
The NodeJS docsstress that the binarystring encoding is heavily discouraged since it will be dropped at some point in the future.
该的NodeJS文档强调,binary字符串编码在很大程度上气馁,因为这将在未来的某一时刻被丢弃。
However, I'm trying to generate image thumbnails with the node-imagemagickmodule, which can only output binaryencoded strings.
但是,我正在尝试使用该node-imagemagick模块生成图像缩略图,该模块只能输出binary编码字符串。
My end goal is to submit the generated thumbnail as a BLOB into a SQLite3 database (I'm using node-sqlite3), so I figured I need the thumbnail as a binary Buffer object.
我的最终目标是将生成的缩略图作为 BLOB 提交到 SQLite3 数据库(我正在使用node-sqlite3),所以我想我需要缩略图作为二进制 Buffer 对象。
How do I directly decode the binaryencoded output from node-imagemagickinto a raw binary Buffer (not just a Buffer that contains a binaryencoded string)? I'm not keen on using base64...
如何将binary编码输出直接解码node-imagemagick为原始二进制缓冲区(不仅仅是包含binary编码字符串的缓冲区)?我不热衷于使用base64...
回答by Esailija
var buffer = new Buffer(binaryString, "binary");
Tested with:
测试:
$ node
> var binaryString = "\xff\xfa\xc3\x4e";
> var buffer = new Buffer(binaryString, "binary");
> console.log(buffer);
<Buffer ff fa c3 4e>
回答by Walter
I don't use node's Buffer for encoding.
我不使用节点的缓冲区进行编码。
You can try iconv-lite(https://www.npmjs.com/package/iconv-lite) should this ever start to fail:
如果这开始失败,您可以尝试iconv-lite(https://www.npmjs.com/package/iconv-lite):
var encode = require("iconv-lite");
var binaryString = "\xff\xfa\xc3\x4e";
var buffer = encode(binaryString, "binary");
console.log(buffer);
// Prints <Buffer ff fa c3 4e>
UPDATEThe iconv-litelibrary has switched to es6 syntax now. So following code won't work. You have to do something like:
更新该iconv-lite库现在已切换到 es6 语法。所以下面的代码将不起作用。您必须执行以下操作:
import { encode } from "iconv-lite";
Not gonna update my code as this will constantly change. Consult documentation: https://github.com/ashtuchkin/iconv-lite
不会更新我的代码,因为这会不断变化。查阅文档:https: //github.com/ashtuchkin/iconv-lite

