我制作了这个简单的 node.js 应用程序:
var express = require('express');
var app = express();
var alasql = require('alasql');
var url = require('url');
var port = 3000;
app.get('/getuser', function(request, response) {
var queryObject = url.parse(request.url, true).query;
var country = queryObject.country;
var nameset = queryObject.nameset;
var state = queryObject.state;
var selectAll;
if (country == "US" && state !== null && state !== "") {
alasql.promise("SELECT * from JSON('database.json') WHERE Country = ? AND NameSet = ? AND State = ?", [country, nameset, state]).
then(function(res) {
if (res !== null && res.length > 0) {
var result = res[Math.floor(Math.random() * res.length + 1)];
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end(JSON.stringify(result));
} else {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end("noresults");
}
}).catch(function(err) {
console.log('Does the database.json file exists? there was an error:', err);
});
} else {
alasql.promise("SELECT * from JSON('database.json') WHERE Country = ? AND NameSet = ?", [country, nameset]).
then(function(res) {
if (res !== null && res.length > 0) {
var result = res[Math.floor(Math.random() * res.length + 1)];
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end(JSON.stringify(result));
} else {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end("noresults");
}
}).catch(function(err) {
console.log('Does the database.json file exists? there was an error:', err);
});
}
});
app.listen(port);
如您所见,我加载了 database.json 文件,对其进行了一些 alasql 查询并将该数据作为响应返回。database.json 的大小约为 50MB。我的问题是这个应用程序使用了 400-600MB 的 RAM!
我也制作了这个版本,我使用 .require 打开 database.json 文件,但是内存消耗是一样的!
var express = require('express');
var app = express();
var alasql = require('alasql');
var url = require('url');
var port = 3000;
var database = require('./database.json');
app.get('/getuser', function(request, response) {
var queryObject = url.parse(request.url, true).query;
var country = queryObject.country;
var nameset = queryObject.nameset;
var state = queryObject.state;
var selectAll;
if (country == "US" && state !== null && state !== "") {
selectAll = alasql("SELECT * from ? WHERE Country = ? AND NameSet = ? AND State = ?", [database, country, nameset, state]);
} else {
selectAll = alasql("SELECT * from ? WHERE Country = ? AND NameSet = ?", [database, country, nameset]);
}
if (selectAll !== null && selectAll.length > 0) {
var res = selectAll[Math.floor(Math.random() * selectAll.length + 1)];
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end(JSON.stringify(res));
} else {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end("noresults");
}
});
app.listen(port);
我做错了什么,我想这是关于我的 JSON 文件大小的一些问题?它是 55000 条记录的数组,每条记录有 20 个字段,如果该信息对您有帮助吗?