Miljac
Miljac

Reputation: 2045

How to export functions from modules in node.js

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):

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?

Upvotes: 0

Views: 228

Answers (1)

Lee
Lee

Reputation: 3101

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;

Upvotes: 1

Related Questions