javascript - 使用 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;
}
解决方案
Node.js 是单线程的,如果你的代码长时间阻塞线程,它会给你一个超时错误。您的代码有两个问题。
- 您正在使用
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);
});
- 排序数据也是线程阻塞任务尝试不同的排序技术,它不会长时间占用线程。
注意:Node.js 不适用于以 CPU 为中心的任务,例如排序、图像处理等。它适用于 I/O 任务。
推荐阅读
- r - 如何使用 R 求解多元多项式回归中的最大值(回归峰值)?
- bash - 使用 curl 自动点击
- encoding - 如何将整数编码为其他整数?
- amazon-web-services - 如何在不配置的情况下使用 Amplify?
- apostrophe-cms - Apostrophe-CMS 渲染小部件模板
- c# - 设置对象数组中每个项目的属性(C#,Regex.Split())
- php - PHP - 替换我的一段字符串
- c++ - Unordered_map 使用 2D 点进行查找
- python - 在 django 中填充字段(添加新的)
- javascript - 使用 Canvas 中的单个按钮一个接一个地调用多个方法来为伪代码设置动画