节点.js全局变量属性被清除

Node.js global variable property is purged

本文关键字:清除 属性 全局变量 js 节点      更新时间:2023-09-26

我的问题不是关于"内存泄漏",而是关于node.js(expressjs)应用程序的"内存清除"。

我的应用应在内存中维护一些对象,以便在服务期间快速查找。 在启动应用程序后的暂时(一两天),一切似乎都很好,直到突然我的 Web 客户端无法查找对象,因为它已被清除(未定义)。 我怀疑Javascript GC(垃圾收集)。 但是,正如您在 psedu 代码中看到的那样,我将对象分配给节点.js"全局"变量属性以防止 GC 清除它们。 请给我一些导致此问题的线索。

提前感谢您的指教~

我的节点.js环境是node.js 0.6.12,expressjs 2.5.8和VMWare cloudfoundry节点托管。

这是我的应用程序.js伪代码:

var express = require("express");
var app = module.exports = express.createServer();
// myMethods holds a set of methods to be used for handling raw data.
var myMethods = require("myMethods");
// creates node.js global properties referencing objects to prevent GC from purging them
global.myMethods = myMethods();
global.myObjects = {};
// omited the express configurations
// creates objects (data1, data2) inside the global.myObjects for the user by id.
app.post("/createData/:id", function(req, res) {
    // creates an empty object for the user.
    var myObject = global.myObjects[req.prams.id] = {};
    // gets json data.
    var data1 = JSON.parse(req.body.data1);
    var data2 = JSON.parse(req.body.data2);
    // buildData1 & buildData2 functions transform data1 & data2 into the usable objects.
    // these functions return the references to the transformed objects.
    myObject.data1 = global.myMethods.buildData1(data1);
    myObject.data2 = global.myMethods.buildData2(data2);
    res.send("Created new data", 200);
    res.redirect("/");
});
// returns the data1 of the user.
// Problem occurs here : myObject becomes "undefined" after one or two days running the service.
app.get("/getData1/:id", function(req, res) {
    var myObject = global.myObjects[req.params.id];
    if (myObject !== undefined) {
        res.json(myObject.data1);
    } else {
        res.send(500); 
    }
});
// omited other service callback functions.
// VMWare cloudfoundry node.js hosting.
app.listen(process.env.VCAP_APP_PORT || 3000);

任何类型的缓存系统(无论是自己的滚动还是第三方产品)都应该考虑这种情况。不应依赖内存中缓存上始终可用的数据。有太多的事情可能导致内存中数据消失(计算机重新启动,进程重新启动等)。

在您的情况下,您可能需要更新代码以查看数据是否在缓存中。如果它不在缓存中,则从持久存储(数据库、文件)中获取它,缓存它,然后继续。

就像Haesung一样,我想保持我的程序简单,没有数据库。就像Haesung一样,我对Node的第一次体验.js(和表达)就是观察这种奇怪的清洗。虽然我很困惑,但我真的不接受我需要一种存储解决方案来管理几百行的 json 文件。对我来说,灯泡时刻是当我读到这篇文章的时候

如果要让模块多次执行代码,请导出一个函数,然后调用该函数。

取自 http://nodejs.org/api/modules.html#modules_caching。所以我在所需文件中的代码从这里更改

var foo = [{"some":"stuff"}];
export.foo;

到那个

export.foo = function (bar) {
var foo = [{"some":"stuff"}];
return foo.bar;
}

然后它工作得很好:-)

然后我建议使用文件系统,我认为 4KB 开销对于您的目标和硬件来说没什么大不了的。如果你熟悉前端javascript,这可能会有所帮助 https://github.com/coolaj86/node-localStorage