【问题标题】:Nodejs: RangeError: Maximum call stack size exceeded at Object.stringify (native)Nodejs:RangeError:Object.stringify(本机)超出了最大调用堆栈大小
【发布时间】:2018-02-08 05:16:01
【问题描述】:

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

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)

有什么办法吗?

【问题讨论】:

    标签: node.js node-streams


    【解决方案1】:

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

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

    这是我的代码,试试看:

    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);
            }
        }();
    
    }
    

    【讨论】:

    • 谢谢你的替代方案,但我得到了同样的错误: if (!writeable.write(JSON.stringify(val) + ',\n')) { ^ RangeError: Maximum call stack size exceeded
    • 这很奇怪,我用数组中的 6000 个对象对其进行了测试,没有任何问题。你不是有机会多次调用 stringifyArrayToFile 函数吗?在某个循环或什么的?您可能希望在使用该函数的位置添加代码,以便我们可以看到一些上下文。你的可用内存没有用完吗?
    • 每个块有多大或数组中的每个对象有多大?如果有巨大的物体,那么它可能是错误的原因。
    • 对不起,代码是正确的,其他功能有错误...错误信息具有误导性...
    猜你喜欢
    • 2016-09-26
    • 1970-01-01
    • 2017-07-02
    • 2020-11-19
    • 2013-08-23
    • 2021-09-07
    • 2017-11-12
    • 2015-03-15
    • 1970-01-01
    相关资源
    最近更新 更多