Wexo Wexo - 1 year ago 323
Javascript Question

NodeJS TypeError: Cannot read property of undefined

so I just started using NodeJs still have a lot to learn but am loving it so far I ran into this problem I found an answer, but it's not what I want it's kinda weird, let me show some code and explain

So I got 2 files

File 1 > app.js (Main)

File 2 > UserEntity.js (Module)


var uEntity = require('./UserEntity.js');

var hm = new uEntity.person();


function User() {
this.info = {
'strUsername': 'Hashimoro'

module.exports.person = User;

I am creating a new UserEntity I want to access the info directly as you can see from the code

But it gives this error:


TypeError: Cannot read property 'strUsername' of undefined
at Object.<anonymous> (D:\NodeLearn\Testing\app.js:4:20)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3

If someone can give a fix and explain would be great

Thank you, seriously appreciate it

Answer Source

This looks a little different from how Node modules are typically written.

There's a great resource on how to write them here.

You can refactor to something like this:


function User() {
  this.info = {
    'strUsername': 'Hashimoro'

User.prototype.getInfo = function() {
  return this.info;

module.exports = User;


var Person = require('./UserEntity.js');
var person = new Person();


// OR
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download