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

前端 未结 2 1092
离开以前
离开以前 2020-12-13 06:01

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

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

2条回答
  •  时光说笑
    2020-12-13 06:55

    Here is an example of fs.read()-ing the first 100 bytes from a file descriptor returned by 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));
        });
    });
    

提交回复
热议问题