我在Node.js的實現我自己的reading a number of bytes of a file版本在這裏與a recursive loop:如何在EOF達到時停止在Node.js中讀取大型二進制文件?
var fs = require("fs");
read = function(fd){
var buffer = new Buffer(637); //some arbitrary number, longer than the file itself.
console.log(fd)
fs.read(fd, buffer, 0, 637, null, function(err, num) {
console.log(buffer);
read(fd)
});
}
fs.open("abinaryfile.mcpr", "r", function(status, fd) {
if (status) {
console.log(status.message);
return;
}
read(fd)
});
但是,當它運行時,它打印出來的文件,但一旦超過了文件的長度隨機緩衝器(胡言亂語)出現(s)。爲了說明這一點更好,我已經放在一個文本文件,而不是在這裏並使用.toString()
上面的代碼讀取它(實際上,我讀了大量的二進制文件):
This is a test.
Everything is good so far.
However, for some reason the code doesn't stop when the end of file is reached.
How can I implement this? (stop reading the file into the buffer when the end of file is reached)
3
���� *�6 ��e� ʙ6�������� �ʙ6 Ǚ6 �ș ��� �t&�
3
`ř6 `ə6 �˙6 �י6 �י6 �ə6 �Ǚ6 �ə6 Ǚ6 '
等等,等等 - 程序打印隨機緩衝區永遠。
不幸的是,我不能implement the solution described here,作爲buffers can only store a maximum of 1GB,而我的真正的二進制文件大於1GB。
如何在文件到達時停止將文件讀入緩衝區?
您的遞歸循環沒有退出條件,它將永遠循環,最終導致應用程序崩潰。請參閱[mmap()](https://www.npmjs.com/package/mmap)將大文件直接加載到內存中。 – Fabien
@Fabien你知道如何確定EOF已經到達的那個循環嗎? 'err'只是保持'空'。 – EnragedViper
是的,無論你跟蹤了多少已被讀取總文件大小,或者你使用[readFile()](https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback) – Fabien