读取大文本文件的n行

gsa*_*ras 9 html javascript io file bigdata

我拥有的最小文件有> 850k行,每行的长度未知.目标是n在浏览器中读取此文件中的行.完全阅读它不会发生.

这是<input type="file" name="file" id="file">我和我的HTML 和JS:

var n = 10;
var reader = new FileReader();
reader.onload = function(progressEvent) {
  // Entire file
  console.log(this.result);

  // By lines
  var lines = this.result.split('\n');
  for (var line = 0; line < n; line++) {
    console.log(lines[line]);
  }
};
Run Code Online (Sandbox Code Playgroud)

显然,这里的问题是它试图首先实现整个文件,然后用换行符拆分它.所以无论如何n,它都会尝试读取整个文件,并在文件很大时最终不读取任何内容.

我该怎么办?

注意:我愿意删除整个函数并从头开始,因为我将能够console.log()读到我们读过的每一行.


*"每行都是未知长度" - >表示文件是这样的:

(0, (1, 2))
(1, (4, 5, 6))
(2, (7))
(3, (8))
Run Code Online (Sandbox Code Playgroud)

编辑:

要走的路就像大文件上的filereader api,但我看不出如何修改它来读取n文件的行...

通过使用Uint8Array在Javascript中字符串,可以从那里做:

var view = new Uint8Array(fr.result);
var string = new TextDecoder("utf-8").decode(view);
console.log("Chunk " + string);
Run Code Online (Sandbox Code Playgroud)

但这可能无法读取整个最后一行,那么您将如何确定以后的行?例如,这是它打印的内容:

((7202), (u'11330875493', u'2554375661'))
((1667), (u'9079074735', u'6883914476',
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 12

逻辑非常类似于我在大文件上filereader api的回答中所写的内容,除了你需要跟踪到目前为止已处理的行数(以及到目前为止读取的最后一行,因为它可能不是已经结束了).下一个示例适用于与UTF-8兼容的任何编码; 如果您需要其他编码,请查看TextDecoder构造函数的选项.

如果确定所述输入是ASCII(或任何其它单字节编码),则还可以跳过使用的TextDecoder和直接读出输入作为使用文本FileReaderreadAsText方法.

// This is just an example of the function below.
document.getElementById('start').onclick = function() {
    var file = document.getElementById('infile').files[0];
    if (!file) {
        console.log('No file selected.');
        return;
    }
    var maxlines = parseInt(document.getElementById('maxlines').value, 10);
    var lineno = 1;
    // readSomeLines is defined below.
    readSomeLines(file, maxlines, function(line) {
        console.log("Line: " + (lineno++) + line);
    }, function onComplete() {
        console.log('Read all lines');
    });
};

/**
 * Read up to and including |maxlines| lines from |file|.
 *
 * @param {Blob} file - The file to be read.
 * @param {integer} maxlines - The maximum number of lines to read.
 * @param {function(string)} forEachLine - Called for each line.
 * @param {function(error)} onComplete - Called when the end of the file
 *     is reached or when |maxlines| lines have been read.
 */
function readSomeLines(file, maxlines, forEachLine, onComplete) {
    var CHUNK_SIZE = 50000; // 50kb, arbitrarily chosen.
    var decoder = new TextDecoder();
    var offset = 0;
    var linecount = 0;
    var linenumber = 0;
    var results = '';
    var fr = new FileReader();
    fr.onload = function() {
        // Use stream:true in case we cut the file
        // in the middle of a multi-byte character
        results += decoder.decode(fr.result, {stream: true});
        var lines = results.split('\n');
        results = lines.pop(); // In case the line did not end yet.
        linecount += lines.length;
    
        if (linecount > maxlines) {
            // Read too many lines? Truncate the results.
            lines.length -= linecount - maxlines;
            linecount = maxlines;
        }
    
        for (var i = 0; i < lines.length; ++i) {
            forEachLine(lines[i] + '\n');
        }
        offset += CHUNK_SIZE;
        seek();
    };
    fr.onerror = function() {
        onComplete(fr.error);
    };
    seek();
    
    function seek() {
        if (linecount === maxlines) {
            // We found enough lines.
            onComplete(); // Done.
            return;
        }
        if (offset !== 0 && offset >= file.size) {
            // We did not find all lines, but there are no more lines.
            forEachLine(results); // This is from lines.pop(), before.
            onComplete(); // Done
            return;
        }
        var slice = file.slice(offset, offset + CHUNK_SIZE);
        fr.readAsArrayBuffer(slice);
    }
}
Run Code Online (Sandbox Code Playgroud)
Read <input type="number" id="maxlines"> lines from
<input type="file" id="infile">.
<input type="button" id="start" value="Print lines to console">
Run Code Online (Sandbox Code Playgroud)

  • @gsamaras当您将“maxlines”设置为任意高的值(例如“Infinity”)时,所有涉及“maxlines”的条件都将计算为 false,因此您可以想象包含它们的“if”块不存在。然后应该很容易看出,“seek”仅在读取到文件末尾(“offset &gt;= file.size”)时才会返回。 (2认同)

Maž*_*ius 5

我需要在浏览器中读取 250MB utf-8 编码的文件。我的解决方案是编写类似于 TextReader 类的 C# 类,该类为我提供了类似异步流的行为。


文本阅读器类:

class TextReader {
    CHUNK_SIZE = 8192000; // I FOUND THIS TO BE BEST FOR MY NEEDS, CAN BE ADJUSTED
    position = 0;
    length = 0;

    byteBuffer = new Uint8Array(0);

    lines = [];
    lineCount = 0;
    lineIndexTracker = 0;

    fileReader = new FileReader();
    textDecoder = new TextDecoder(`utf-8`);

    get allCachedLinesAreDispatched() {
        return !(this.lineIndexTracker < this.lineCount);
    }

    get blobIsReadInFull() {
        return !(this.position < this.length);
    }

    get bufferIsEmpty() {
        return this.byteBuffer.length === 0;
    }

    get endOfStream() {
        return this.blobIsReadInFull && this.allCachedLinesAreDispatched && this.bufferIsEmpty;
    }

    constructor(blob) {
        this.blob = blob;
        this.length = blob.size;
    }

    blob2arrayBuffer(blob) {
        return new Promise((resolve, reject) => {
            this.fileReader.onerror = reject;
            this.fileReader.onload = () => {
                resolve(this.fileReader.result);
            };

            this.fileReader.readAsArrayBuffer(blob);
        });
    }

    read(offset, count) {
        return new Promise(async (resolve, reject) => {
            if (!Number.isInteger(offset) || !Number.isInteger(count) || count < 1 || offset < 0 || offset > this.length - 1) {
                resolve(new ArrayBuffer(0));
                return
            }

            let endIndex = offset + count;

            if (endIndex > this.length) endIndex = this.length;

            let blobSlice = this.blob.slice(offset, endIndex);

            resolve(await this.blob2arrayBuffer(blobSlice));
        });
    }

    readLine() {
        return new Promise(async (resolve, reject) => {

            if (!this.allCachedLinesAreDispatched) {
                resolve(this.lines[this.lineIndexTracker++] + `\n`);
                return;
            }

            while (!this.blobIsReadInFull) {
                let arrayBuffer = await this.read(this.position, this.CHUNK_SIZE);
                this.position += arrayBuffer.byteLength;

                let tempByteBuffer = new Uint8Array(this.byteBuffer.length + arrayBuffer.byteLength);
                tempByteBuffer.set(this.byteBuffer);
                tempByteBuffer.set(new Uint8Array(arrayBuffer), this.byteBuffer.length);

                this.byteBuffer = tempByteBuffer;

                let lastIndexOfLineFeedCharacter = this.byteBuffer.lastIndexOf(10); // LINE FEED CHARACTER (\n) IS ONE BYTE LONG IN UTF-8 AND IS 10 IN ITS DECIMAL FORM

                if (lastIndexOfLineFeedCharacter > -1) {
                    let lines = this.textDecoder.decode(this.byteBuffer).split(`\n`);
                    this.byteBuffer = this.byteBuffer.slice(lastIndexOfLineFeedCharacter + 1);

                    let firstLine = lines[0];

                    this.lines = lines.slice(1, lines.length - 1);
                    this.lineCount = this.lines.length;
                    this.lineIndexTracker = 0;

                    resolve(firstLine + `\n`);
                    return;
                }
            }

            if (!this.bufferIsEmpty) {
                let line = this.textDecoder.decode(this.byteBuffer);
                this.byteBuffer = new Uint8Array(0);
                resolve(line);
                return;
            }

            resolve(null);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

document.getElementById("read").onclick = async () => {
    let file = document.getElementById("fileInput").files[0];
    let textReader = new TextReader(file);

    while(true) {
        let line = await textReader.readLine();
        if(line === null) break;
        // PROCESS LINE
    }

    // OR

    while (!textReader.endOfStream) {
        let line = await textReader.readLine();
        // PROCESS LINE
    }
};
Run Code Online (Sandbox Code Playgroud)

表现:

我能够在大约 1.5 秒内读取包含 1,398,258 行的单个 250MB utf-8 编码文本文件,其中 JS 堆大小不超过 20MB。相比之下,如果我一次性读取同一个文件,然后用\n分割结果字符串,仍然需要大约 1.5 秒,但是 JS 堆会达到 230MB。