2017-08-15 54 views
-1

我在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。

如何在文件到達時停止將文件讀入緩衝區?

+0

您的遞歸循環沒有退出條件,它將永遠循環,最終導致應用程序崩潰。請參閱[mmap()](https://www.npmjs.com/package/mmap)將大文件直接加載到內存中。 – Fabien

+0

@Fabien你知道如何確定EOF已經到達的那個循環嗎? 'err'只是保持'空'。 – EnragedViper

+0

是的,無論你跟蹤了多少已被讀取總文件大小,或者你使用[readFile()](https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback) – Fabien

回答

0

您的遞歸循環沒有退出條件,它將永遠循環,最終導致應用程序崩潰。

你要跟蹤你有多少字節讀取超過總文件大小,或使用替代的API,例如:

mmap()大型文件直接加載到內存中。

readFile()一次讀取整個文件。

請記住,fs.read()是一個非常低級的API,因此它不會在EOF上觸發任何事情。

+0

'readFile()'崩潰與' RangeError:文件大小大於可能的緩衝區:0x7fffffff bytes',我不相信mmap可以在Windows上運行,但是我會嘗試跟蹤讀取的字節數並查看它是否有效。 – EnragedViper

+0

您是否在Windows上運行32位NodeJS?: -/ – Fabien

+0

不,Windows上的64位Node.js。 – EnragedViper