【问题标题】:Synchronously read file and convert to byte-array同步读取文件并转换为字节数组
【发布时间】:2018-01-29 21:36:24
【问题描述】:

我正在使用Node.js 压缩一些文件并将它们的原始字节数组输出到一个文件中。

例如:

test.txt:

1234

text.txt > test.txt.gz

test.txt.gz 转字节数组> array.txt

array.txt:

{0x66,0x75,0x6e,0x63,0x74,0x69,0x6f,0x6e}


我似乎找不到关于将文件转换为字节数组或任何 npm 包的任何其他问题。我试图手动 fs.readFileSync 一个文件并在函数中使用它,但由于特殊字符和编码失败。

如何在 Node.js 中原生或使用包将文件转换为字节数组?

【问题讨论】:

  • 也许你想检查我的编辑,它提供了一种简单快速的方法来制作一个字节数组

标签: javascript arrays node.js hex byte


【解决方案1】:

我认为这完成了你想要的,虽然有点脏。

仅供参考:fs.readFileSync 返回一个Buffer 对象,您可以通过Buffer.toString('hex') 将其转换为十六进制

var fs = require('fs');

function getByteArray(filePath){
    let fileData = fs.readFileSync(filePath).toString('hex');
    let result = []
    for (var i = 0; i < fileData.length; i+=2)
      result.push('0x'+fileData[i]+''+fileData[i+1])
    return result;
}

result = getByteArray('/path/to/file')
console.log(result)

【讨论】:

    【解决方案2】:

    示例:

    console.log("[string]:")
    const _string = 'aeiou.áéíóú.äëïöü.ñ';
    console.log(_string)
    
    console.log("\n[buffer]:")
    const _buffer = Buffer.from(_string, 'utf8');
    console.log(_buffer)
    
    console.log("\n[binaryString]:")
    const binaryString = _buffer.toString();
    console.log(binaryString)
    

    输出:

    [string]:
    aeiou.áéíóú.äëïöü.ñ
    
    [buffer]:
    <Buffer 61 65 69 6f 75 2e c3 a1 c3 a9 c3 ad c3 b3 c3 ba 2e c3 a4 c3 ab c3 af c3 b6 c3 bc 2e c3 b1>
    
    [binaryString]:
    aeiou.áéíóú.äëïöü.ñ
    

    编辑:convert-string 很容易

    例子:

    console.log("[string]:")
    const _string = 'aeiou.áéíóú.äëïöü.ñ';
    console.log(_string)
    
    console.log("\n[byteArray]:")
    const converter = require('convert-string')
    const byteArray = converter.UTF8.stringToBytes(_string)
    console.log(byteArray)
    

    输出:

    [byteArray]:
    [ 97,
      101,
      105,
      111,
      117,
      46,
      195,
      161,
      195,
      169,
      195,
      173,
      195,
      179,
      195,
      186,
      46,
      195,
      164,
      195,
      171,
      195,
      175,
      195,
      182,
      195,
      188,
      46,
      195,
      177 ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      相关资源
      最近更新 更多