简体   繁体   English

node.js缓存与module.exports有关的问题

[英]nodejs cache issue with module.exports

I am a newbie in nodejs. 我是nodejs的新手。

I have this Script: book.js 我有这个脚本: book.js

var page = 0;

exports.setPageCount = function (count) {
    page = count; 
}

exports.getPageCount = function(){
    return page;
}

Along with the follownig script: scripts.js 以及以下脚本: scripts.js

var bookA = require('./book');

var bookB = require('./book');

bookA.setPageCount(10);

bookB.setPageCount(20);

console.log("Book A Pages : " + bookA.getPageCount());

console.log("Book B Pages : " + bookB.getPageCount());

The Output I get: 我得到的输出:

Book A Pages : 20
Book B Pages : 20

So, I modified script: 因此,我修改了脚本:

module.exports = function(){
    var page = 0;

    setPageCount  : function(count){
        page = count;
    },

    getPageCount : function(){

        return page;
    }

}

I am expecting the following output: 我期望以下输出:

Book A Pages : 10
Book B Pages : 20

But still getting the original outcome, does anyone have an idea where I made an error? 但是仍然可以得到原始结果,是否有人知道我在哪里出错?

There are a few ways to go about this and your last attempt is almost a valid one -- modify your module like so: 有几种方法可以解决此问题,您的上一次尝试几乎是有效的-像这样修改模块:

module.exports = function() {
  var pages = 0;
  return {
    getPageCount: function() {
      return pages;
    },
    setPageCount: function(p) {
      pages = p;
    }
  }
}

and your usage like so: 和你的用法是这样的:

var bookFactory = require('./book');
var bookA = bookFactory();
var bookB = bookFactory();
bookA.setPageCount(10);
bookB.setPageCount(20);
console.log("Book A Pages : " + bookA.getPageCount());
console.log("Book B Pages : " + bookB.getPageCount());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM