简体   繁体   中英

nodejs cache issue with module.exports

I am a newbie in nodejs.

I have this Script: book.js

var page = 0;

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

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

Along with the follownig script: 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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