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

1 Answer 1

3

Change out

module.exports.validator = validateCustomer;

for

module.exports = validateCustomer

in validator.js.

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks.. it works.. but can you explain why i cannot use module.exports.validator = validateCustomer ?
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.
Please check my updated comment. I try to set validator = validateCustomer which is my function
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.
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()
|

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.