Node.js内存泄漏?

Rob*_*Rob 11 javascript memory-leaks node.js express

我在我的Express.js应用程序中使用了一些代码来集中一些acl逻辑.如果函数返回truefalse显式中间件可以处理next调用.但是如果它没有返回,那么next()只要它完成了它就完成了授权逻辑.

为了避免写出错误数据,我想传入一个error()可以调用的next函数,它只是在内部调用函数.

有人告诉我,这可能导致某种内存泄漏,因为next函数在它自己的闭包中并从外部引用它.我看到在网上的很多例子中使用了类似的技术,但我对Node.js还是很陌生,所以想知道这是否有任何道理?

this.router.use(function (req, res, next) {
    var err = {
            code: 403,
            exception: 'UnauthorizedException',
            data: {}
        },
        error = function () {
            next(err);
        },
        authorize = app.route.authorize(req, res, next, error);

    if (authorize === false) {
        next(err);
    }
    else if (authorize === true) {
        next();
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑:删除变量

this.router.use(function (req, res, next) {
    var authorize = app.route.authorize(req, res, next, function () {
        next({
            code: 403,
            exception: 'UnauthorizedException',
            data: {}
        });
    });

    if (authorize === false) {
        next({
            code: 403,
            exception: 'UnauthorizedException',
            data: {}
        });
    }
    else if (authorize === true) {
        next();
    }
});
Run Code Online (Sandbox Code Playgroud)

Dav*_*son 5

当您设置中间件时,该.use()方法在那里被调用一次,匿名处理程序/中间件被写入内存一次,并且它是为每个新请求调用的相同中间件函数.

err变量被实例化每一个中间件运行时,这是一个不同的对象.如果你把它放在外面并进入封闭范围.use(),那么它将是同一个对象.

然后,它被传递到nextnext极有可能是被实例化一次,并保持相同的内存,其持续和劫掠其关闭访问的另一个中间件功能.

但是,当next函数完成运行时,err指向的对象将丢失其引用 - 它应该被垃圾收集.