使用 NestJS 和 MongoDB 读取、解析文件和插入文档导致 JavaScript 堆内存不足

问题描述

我的 NestJS 应用程序有一个简单的目的:

  • 遍历一组大文件(29 个文件,每个文件大约有 12k 到 70k 行)
  • 逐行读取文件并解析
  • 将(每一行)插入到我的 MongoDB 集合中

我的代码中最重要的部分包括:

    for(let file of FILES){
                    result = await this.processFile(file);
                    resultInsert += result;
    }

和函数 processFile()

    async processFile(fileName: string): Promise<number> {
            count = 0;
    
            return new Promise((resolve,reject) => {
                let s = fs
                .createReadStream(BASE_PATH + fileName,{encoding: 'latin1'})
                .pipe(es.split())
                .pipe(
                    es
                        .mapSync(async (line: string) => {
                            
                            count++;
                            console.log(line);
                            let line_splited = line.split("@");                            
                            let user = {
                                name: line_splited[0],age: line_splited[1],address: line_splited[2],job: line_splited[3],country: line_splited[4]
                            }
                            
                            await this.userModel.updateOne(
                                user,user,{ upsert: true }
                            );
                                    
                               
                        })
                        .on('end',() => {
                            resolve(count);
                        })
                        .on('error',err => {
                            reject(err);
                        })
                );    
            });
        }

主要问题是通过 ~9th 文件的交互,我有一个内存失败:分配失败 - JavaScript 堆内存不足。 我发现我的问题与 Parsing huge logfiles in Node.js - read in line-by-line 类似,但代码仍然失败。

我怀疑我正在打开一个文件,读取它,当我打开另一个文件时,我仍然插入前一个文件可能会导致问题,但我不知道如何处理。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)