0

I am trying to follow the tutorial at the following link about extending modules in JS. https://www.guru99.com/node-js-modules-create-publish.html and the codes are

Tutorial.js

var exports=module.exports={};
exports.tutorial=function()
{
console.log("Guru99 Tutorial")
}

NodeTutorial.js

var Tutor=require('./Tutorial.js');
exports.NodeTutorial=function()
{
console.log("Node Tutorial")
function pTutor()
{
var PTutor=Tutor
PTutor.tutorial();
}
}

App.JS

var localTutor=require('./NodeTutorial.js');
localTutor.NodeTutorial();
localTutor.NodeTutorial.pTutor();

it give the error of

localTutor.NodeTutorial.pTutor(); is not a function

so I searched at this forum and found this same code syntax with same issue Extending Module in nodejs gives error and according to the answer, I changed the code to

this.pTutor = function(){
var PTutor=Tutor
PTutor.tutorial();
}

and

var localTutor = new require('./NodeTutorial.js');
localTutor.NodeTutorial();
localTutor.pTutor();

so what I would like to ask is the syntax of extending modules change or what is the problem here? Is the way from tutorial no longer work?

echo
  • 41
  • 1
  • 5
  • 1
    "Is the way from tutorial no longer work?" - it never worked. In order for localTutor.NodeTutorial.pTutor function to be available, there should be "this.pTutor=" or "exports.NodeTutorial.pTutor=" in NodeTutorial.js . The tutorial contains outdated and imprecise code, it shouldn't be used as primary learning source, only probably to confirm that you know things it talks about – Estus Flask Jan 07 '22 at 16:46
  • In the beginning, I also thought it as imprecise code or typo error and slide it off but the stackoverflow post with same problem with exact syntax make me wonder is it the alternate way or old syntax? – echo Jan 07 '22 at 16:52
  • No. Most likely both were pasted from the same wrong piece of code. The only things that are specific to Node here are `require` and `exports` object. Most things you'll learn are specific to JS. In JS, there's no way how pTutor function that is defined inside another function and not made available somehow (`return` or `=`) to the outer world could become exposed . See https://stackoverflow.com/questions/7295634/javascript-nested-function that was linked in related question – Estus Flask Jan 07 '22 at 17:19
  • Thank you for your both time and effort and it is pretty clear for me now. Thank you very much – echo Jan 08 '22 at 10:38

0 Answers0