0

I am using node.js (v4.2.2) with express (4.13.1). I am trying to import my custom module functions to another module. Application is created with express, and only thing added to app.js is require for my route var tests = require('./routes/tests'); and app.use for that route app.use('/tests', tests);

My two custom files (modules) are (path is relative to project root):

  • ./model/test.js
  • ./routes/tests.js

Here is ./model/test.js:

var id;
var testNumber1;
var testNumber2;

function Test(id, testNumber1, testNumber2) {
    this.id = id;
    this.testNumber1 = testNumber1;
    this.testNumber2 = testNumber2;
};

exports.reset = function() {
    this.testNumber1 = 0;
    this.testNumber2 = 0;
};

module.exports = Test;

And here is ./routes/tests.js:

var express = require('express');
var Red = require('../model/test.js');
var router = express.Router();

/*create new test :id*/
router.post('/:id', function(req, res, next) {
  var myNewTest = new Red(req.params.id, 0, 0)
  myNewTest.testNumber2 += 1;
  myNewTest.reset();
  res.send('id: ' + myNewTest.id + 
    ' testNumber2: ' + myNewTest.testNumber2);
});

module.exports = router;

When I try to execute curl -X POST http://localhost:3000/tests/1 i get error TypeError: myNewTest.reset is not a function. I am having trouble understanding how to export functions correctly. If I understand this api reference correctly, to expose constructor of module, i have to use module.exports = Test;, but that doesn't expose reset function. So, to expose it I have declared it like exports.reset = function() {...}, but obviously, that doesn't work, at least not in my case.

Through some other answers I have also seen function being declared normally function reset() {...}, and exposed like exports.reset = reset;, which gives me the same error.

How do I expose reset function properly?

1 Answer 1

1

You should add it to the prototype, at the moment it's just a static method in your module, not attached to the Test constructor.

function Test(id, testNumber1, testNumber2) {
    this.id = id;
    this.testNumber1 = testNumber1;
    this.testNumber2 = testNumber2;
};

Test.prototype.reset = function() {
    this.testNumber1 = 0;
    this.testNumber2 = 0;
};

module.exports = Test;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.