2

I am new to nodejs and I am trying to export my custom module but it says function is not defined or is not a function.

I have created a module which contains a function to validate the request body using Joi library. Below is what I have done

validator.js

const Joi = require('joi');

var validateCustomer = function(customer) {
    const schema = {
        name: Joi.string().min(3).required()
    }

    return Joi.validate(customer, schema)
}

module.exports.validator = validateCustomer;

customers.js

const validator = require('../myModules/validator');

router.post('/', async (req, res) => {
    const {error} = validator(req.body);
    if(error) return res.error(404).send(error.details[0].message);
    ...some code 
});

Please help

girish
  • 302
  • 1
  • 5
  • 17

1 Answers1

3

Change out

module.exports.validator = validateCustomer;

for

module.exports = validateCustomer

in validator.js.

jsarbour
  • 928
  • 1
  • 8
  • 20
  • 1
    Thanks.. it works.. but can you explain why i cannot use module.exports.validator = validateCustomer ? – girish May 29 '19 at 19:29
  • 1
    Well let's think about what that's trying to say. `module.exports.validateCustomer` is looking for the `module` object's `exports` property's `validateCustomer` property. I don't believe that exists in any fashion. As such, you're setting a value that doesn't exist. I reccomend reading up on `module.exports()`, there's a relatively large number of well written guides, all easy to find. – jsarbour May 29 '19 at 19:32
  • 1
    Please check my updated comment. I try to set validator = validateCustomer which is my function – girish May 29 '19 at 19:33
  • by the same reason, you're setting `module.exports.validator`, which is not a field or property that exists. – jsarbour May 29 '19 at 19:34
  • 1
    You're just trying to declare to the larger JS enviroment "this module has a function called this and you're allowed to use it!" There's no need to associate it with anything. – jsarbour May 29 '19 at 19:35
  • 1
    As well, `module` in this case represents the "idea" of `validator.js`, which has some exports, specifically the `validateCustomer` function. It doesn't make sense to say `validator.exports.validator = foo()` – jsarbour May 29 '19 at 19:36
  • I can see something similar explained in this question's accepted answer so i didn't get it https://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it – girish May 29 '19 at 19:41
  • Can you please explain what does that mean in the above question URL? Because i didn't understand it and it is similar to something what I was doing. – girish May 30 '19 at 06:07
  • I'm not sure what you need help with. The question you linked gives a more clear explanation that I could have provided. – jsarbour Jun 03 '19 at 13:01