javascript 如何使用javascript逐字节读取二进制文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15808151/
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 read binary file byte by byte using javascript?
提问by robertklep
I need to read the binary file byte by byte using javascript.I had got below code in this site,but its not working.I think i have to add some extra src file as a reference to it.Please help me to do it.here the code...
我需要使用 javascript 逐字节读取二进制文件。我在本站点中得到了以下代码,但它不起作用。我想我必须添加一些额外的 src 文件作为对它的引用。请帮我做。这里的代码...
var fs = require('fs');
var Buffer = require('buffer').Buffer;
var constants = require('constants');
fs.open("file.txt", 'r', function(status, fd) {
if (status) {
console.log(status.message);
return;
}
var buffer = new Buffer(100);
fs.read(fd, buffer, 0, 100, 0, function(err, num) {
console.log(buffer.toString('utf-8', 0, num));
});
});
回答by robertklep
You can read the file synchronously, byte by byte:
您可以逐字节同步读取文件:
fs.open('file.txt', 'r', function(err, fd) {
if (err)
throw err;
var buffer = new Buffer(1);
while (true)
{
var num = fs.readSync(fd, buffer, 0, 1, null);
if (num === 0)
break;
console.log('byte read', buffer[0]);
}
});
回答by Cigodien
You can use the following code:
您可以使用以下代码:
var blob = file.slice(startingByte, endindByte);
reader.readAsBinaryString(blob);
Here's how it works:
这是它的工作原理:
file.slice
will slice a file into bytes and save to a variable as binary. You can slice by giving the start byte and end byte.reader.readAsBinaryString
will print that byte as binary file. It doesn't matter how big the file is.
file.slice
将文件切成字节并保存为二进制变量。您可以通过提供开始字节和结束字节来切片。reader.readAsBinaryString
将该字节打印为二进制文件。文件有多大并不重要。
For more info, see this link.
有关详细信息,请参阅此链接。