【问题标题】:How to decode "binary" encoded string into raw binary Buffer?如何将“二进制”编码字符串解码为原始二进制缓冲区?
【发布时间】:2012-12-11 16:00:24
【问题描述】:

NodeJS docs 强调 binary 字符串编码是非常不鼓励的,因为它会在将来的某个时候被删除。

但是,我正在尝试使用node-imagemagick 模块生成图像缩略图,该模块只能输出binary 编码字符串。

我的最终目标是将生成的缩略图作为 BLOB 提交到 SQLite3 数据库(我使用的是node-sqlite3),所以我认为我需要将缩略图作为二进制 Buffer 对象。

如何将node-imagemagickbinary 编码输出直接解码为原始二进制缓冲区(不仅仅是包含binary 编码字符串的缓冲区)?我不热衷于使用base64...

【问题讨论】:

    标签: node.js encoding binary imagemagick buffer


    【解决方案1】:
    const buffer = new Buffer(binaryString, "binary");
    

    测试:

    $ node
    > var binaryString = "\xff\xfa\xc3\x4e";
    > var buffer = new Buffer(binaryString, "binary");
    > console.log(buffer);
    <Buffer ff fa c3 4e>
    

    更新:从 v10.0.0 开始 - 改用 Buffer.from(string[, encoding])

    【讨论】:

    • 您没有误解文档。他们明确指出“二进制”编码将被删除!在从 ImageMagick 捕获输出以存储到 MongoDB 时,我也遇到了同样的问题。 “二进制”是唯一一种似乎可以在数据库中正确获取 STDOUT 的编码。那么有什么替代方案呢?
    • @WouterHuysentruit 向 github 上的库作者提出了一个问题,以更新他们的模块以使用缓冲区......它肯定会在 "binary" 从节点中删除之前得到解决?
    【解决方案2】:

    我不使用节点的 Buffer 进行编码。

    如果这开始失败,您可以尝试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>
    

    更新 iconv-lite 库现在已切换到 es6 语法。所以下面的代码是行不通的。您必须执行以下操作:

    import { encode } from "iconv-lite";
    

    不会更新我的代码,因为它会不断变化。查阅文档: https://github.com/ashtuchkin/iconv-lite

    【讨论】:

      【解决方案3】:
      const bin = 'PK\u0003\u0004\n\u0000\u0000\u0000\b\u0000\u0013{yB½g].9\u0001\u0000\u00005\u0004\u0000\u0000\u0013\u0000\u0000\u0000[Content_Types].xml'
      const buf = new Buffer.from(bin, 'binary');
      console.log(buf)
      // <Buffer 50 4b 03 04 0a 00 00 00 08 00 13 7b 79 42 bd 67 5d 2e 39 01 00 00 35 04 00 00 13 00 00 00 5b 43 6f 6e 74 65 6e 74 5f 54 79 70 65 73 5d 2e 78 6d 6c>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-16
        • 2015-02-14
        • 2021-12-02
        • 2014-02-21
        • 2015-12-28
        • 1970-01-01
        • 2016-07-16
        • 2012-09-01
        相关资源
        最近更新 更多