Javascript 如何在 Node.js 中逐字节读取二进制文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5784621/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:49:30  来源:igfitidea点击:

How to read binary files byte by byte in Node.js

javascriptnode.js

提问by Alec Gorge

What is the best way to read part of a binary file in Node.js?

在 Node.js 中读取部分二进制文件的最佳方法是什么?

I am looking to either access specific bytes in the "header" (less than the first 100 bytes) or read the file byte by byte.

我希望访问“标头”中的特定字节(小于前 100 个字节)或逐字节读取文件。

回答by samplebias

Here is an example of fs.read()-ing the first 100 bytes from a file descriptor returned by fs.open():

以下是fs.read()从 返回的文件描述符中-ing 前 100 个字节的示例fs.open()

var fs = require('fs');

fs.open('file.txt', 'r', function(status, fd) {
    if (status) {
        console.log(status.message);
        return;
    }
    var buffer = Buffer.alloc(100);
    fs.read(fd, buffer, 0, 100, 0, function(err, num) {
        console.log(buffer.toString('utf8', 0, num));
    });
});

回答by zwitterion

This is another option

这是另一种选择

const fs = require('fs');

const fileName = 'something.bin'

/*
Requirements ex:
Content in 512 bytes chunks. 
Send the 512 bytes packet as a 1024 char string, where each byte is sent as a 
2 hex digits. 
An "addr" field starts from 0 and tracks the offset of the first byte of the 
packet. 
*/
function chunk(s, maxBytes) {
  //! https://nodejs.org/api/buffer.html#buffer_buf_slice_start_end
  /*
    buf.slice([start[, end]])
    start <integer> Where the new Buffer will start. Default: 0.
    end <integer> Where the new Buffer will end (not inclusive). Default: buf.length.
    Returns: <Buffer>
  */

  let buf = Buffer.from(s);  
  const result = [];
  let readBuffer = true
  let startChunkByte = 0
  let endChunkByte = maxBytes
  while(readBuffer) {
    // First round
    startChunkByte === 0 ? endChunkByte = startChunkByte + maxBytes : ""

    //Handle last chunk
    endChunkByte >= buf.length ? readBuffer = false : ""

    // addr: the position of the first bytes.  raw: the chunk of x bytes
    result.push({"addr":startChunkByte,"raw":buf.slice(startChunkByte, endChunkByte).toString('hex')});

    startChunkByte = endChunkByte
    endChunkByte = startChunkByte + maxBytes
  }
  return result;
}

fs.readFile(fileName, (err, data) => {
  if (err) throw err;
  // Let's choose 512 bytes chunks
  const arrBinChunk =  chunk(data, 512)
  arrBinChunk.forEach(element => console.log(element))

  //Tests - should be able to see 1024, 1024, as per riquerements
  arrBinChunk.forEach(element => console.log(element.raw.length))
});