清除Node.js全局变量属性

时间:2012-06-26 07:28:26

标签: javascript node.js garbage-collection global-variables purge

我的问题不是关于“内存泄漏”,而是关于node.js(expressjs)app的“内存清除”。

我的应用应该在内存中保留一些对象,以便在服务期间快速查找。在启动应用程序后的一段时间(一两天)内,看起来很好,直到突然我的Web客户端无法查找对象,因为它已被清除(未定义)。我怀疑Javascript GC(垃圾收集)。但是,正如您在psedu代码中看到的那样,我将对象分配给node.js“global”变量属性,以防止GC清除它们。请告诉我一些导致这个问题的线索。

非常感谢您的善意建议〜

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

这是我的app.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);

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

与Haesung完全一样,我想保持我的程序简单,没有数据库。和Haesung一样,我对Node.js(和express)的第一次体验是观察这种奇怪的清除。虽然我很困惑,但我真的不接受我需要一个存储解决方案来管理一个有几百行的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;
}

然后它运作良好: - )

答案 2 :(得分:0)

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

相关问题