我想使用类型记录解析/处理一个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;
}发布于 2021-09-09 01:40:42
发布于 2021-09-09 07:38:23
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任务。
https://stackoverflow.com/questions/69111018
复制相似问题