当我调用以下函数将数组对象写入文件时,它在正常大小的数组下正常工作
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)
任何解决方案?