Search code examples
javascriptnode.jses6-modulescommonjs

How to include modules in Node.js


I am learning to develop with Node.js (ie i am a newbie in this technology). I am currently following a french tutorial on Youtube to learn how to use Node.js with Express.

I am trying to include a module to be used to display JSON data, but I keep having an error message. The code of the module is in a file named helper.js The code of the module is the following :

<code>
module.exports = function success(message,data) {
  return {
    message: message,
    data: data
  }
};
</code>

And I try to use the module in my code in the following way :

<code>

const hlp = require('./helper.js')
...

app.get('/api/pokemon/:id',(req,res)=>
{
    var pk = pks.pokemons.find(pokemon=>pokemon.id == parseInt(req.params.id))
    if (pk !== undefined) 
    {
    res.json(hlp.success(msg,pk))
    }
    else
    {
        res.send('You choose a pokemon that does not exist.')
    };
});
</code>

The error message says that hlp.success does not exist. Can you help me on how to include correctly the module helper.js and use it in a correct way ?

Thank you.


Solution

  • You assigned the function to module.exports.

    It's name is irrelevant (unless you see it in a stack trace or want to call it recursively).

    When you hlp = require('./helper.js') you assign the exported function to hlp, not to hlp.success.