0

当我调用以下函数将数组对象写入文件时,它在正常大小的数组下正常工作

function stringifyArrayToFile(array, file) {
    const transform = new stream.Transform({
        objectMode: true
    })
    transform._hasWritten = false
    transform._transform = function (chunk, encoding, callback) {
        if (!this._hasWritten) {
            this._hasWritten = true;
            this.push('[' + JSON.stringify(chunk) + '\n')
        } else {
            this.push(',' + JSON.stringify(chunk) + '\n')
        }
        callback()
    }
    transform._flush = function (callback) {
        this.push(']')
        callback()
    }

    const writeable = fs.createWriteStream(file).setDefaultEncoding("utf-8")
    array.toStream().pipe(transform).pipe(writeable)
}

但是当数组中有大约 5000 个元素时,我会收到以下错误:

this.push('[' + JSON.stringify(chunk) + '\n')
                     ^

RangeError: Maximum call stack size exceeded
    at Object.stringify (native)

任何解决方案?

4

1 回答 1

0

我不确定你的代码有什么问题,但我尝试了下面的代码,它似乎工作得很好。

您能否通过在上面添加来确保this._hasWritten除第一个块之外的所有块都设置为 trueconsole.log(this._hasWritten);if (!this._hasWritten) {

这是我的代码,试一试:

function stringifyArrayToFile(array, file) {

    var writeable = fs.createWriteStream(file).setDefaultEncoding("utf-8");

    writeable.write('[\n');

    !function write() {
        var val = array.pop();
        if (!val)
            return writeable.end(']');

        if (!writeable.write(JSON.stringify(val) + ',\n')) {
            writeable.once('drain', write);
        } else {
            process.nextTick(write);
        }
    }();

}
于 2018-02-07T21:16:01.843 回答