首页 > 解决方案 > 使用 Typescript 解析大 JSON 文件

问题描述

我想使用 Typescript 解析/处理一个 25 MB JSON 文件并过滤/排序对象.. 我编写的代码需要几分钟(有时会超时)不知道为什么会发生这种情况,或者是否有另一种方法可以使代码更多高效的。

注意:代码在一个小文件上工作

import fs from 'fs';
searchAccounts(): Promise<Account[]> {
       const accountSearchCriteria: AccountSearchCriteria = {
                country: 'NZ',
                mfa: 'SMS',
                name: 'TEST',
                sortField: 'dob'
        };
        const jsonPath = './src/file.json';
        const rawAccounts = fs.readFileSync(jsonPath, 'utf-8');
        let accounts: Account[] = JSON.parse(rawAccounts);
        if (accountSearchCriteria) {
            if (accountSearchCriteria.name) {
                accounts = accounts.filter(
                    account =>
                        account.firstName.toLowerCase() ===
                            accountSearchCriteria.name.toLowerCase() ||
                        account.lastName.toLowerCase() ===
                            accountSearchCriteria.name.toLowerCase()
                );
            }
            if (accountSearchCriteria.country) {
                accounts = accounts.filter(
                    account =>
                        account.country.toLowerCase() ===
                        accountSearchCriteria.country.toLowerCase()
                );
            }
            if (accountSearchCriteria.mfa) {
                accounts = accounts.filter(
                    account => account.mfa === accountSearchCriteria.mfa
                );
            }
            if (accountSearchCriteria.sortField) {
                accounts.sort((a, b) => {
                    return a[accountSearchCriteria.sortField] <
                        b[accountSearchCriteria.sortField]
                        ? -1
                        : 1;
                });
            }
            return accounts;
        }
        return accounts;
}

标签: javascriptnode.jsjsontypescriptfilestream

解决方案


Node.js 是单线程的,如果你的代码长时间阻塞线程,它会给你一个超时错误。您的代码有两个问题。

  1. 您正在使用fs.readFileSync(jsonPath, 'utf-8');,它是一个异步函数,并在读取文件时阻塞线程。改用fs.readFile('./Index.html', callback)
const fs = require('fs');
fs.readFile('./Index.html', function read(err, data) {
   if (err) {
       throw err;
   }
   console.log(data);
});
  1. 排序数据也是线程阻塞任务尝试不同的排序技术,它不会长时间占用线程。

注意:Node.js 不适用于以 CPU 为中心的任务,例如排序、图像处理等。它适用于 I/O 任务。


推荐阅读