简体   繁体   中英

JavaScript / How create a new object in node.js?

I have the following code in node.js , using express :

app.post('/printUp', function(req, res) {
    var multipl = new require('./multUploud').printNum(req, res);
})

and i have the following in my multUploud.js:

var partNum = 0;
module.exports = {
     printNum: function (req, res){
        partNum ++;
        console.log(partNum);
    }
}

If I sent two commands of post, I see that partNum is 1 in the first iteration, and 2 in the second.

is there any option to create a new instance for every app.post request, so it prints 1 and 1?

Just make partNum a property of your object. Your multUploud.js should look somewhat like that:

module.exports = MultiUpload;

function MultiUpload() {
  this.partNum = 0;
}

MultiUpload.prototype.printNum = function (req, res) {
  this.partNum++;
  console.log(this.partNum);
}

Then, in your Express post:

app.post('/printUp', function(req, res) {
    var MultiUpload = require('./multUploud');
    var multipl = new MultiUpload();
    multipl.printNum(req, res);
})

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