我制作了这个简单的node.js app:
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个字段,如果该信息对您有帮助吗?
答案 0 :(得分:3)
事实上它在磁盘上是50mb,在与内存进行比较时并不是特别有用。
根据数据库JSON中的内容,它可能远大于磁盘表示。
以整数为例,如果JSON中的值为5
,则ASCII中只占用1个字节,但在Javascript中占用8个字节,因为所有数字都是8个字节。当你考虑跟踪JSON对象本身及其子等所需的引用数量时,你最终会得到比磁盘表示更大的东西。