pig__man pig__man - 1 year ago 68
Javascript Question

Called local class with Node

I'm having a small issue with node and calling a local class in another file from app.js,

For example


class bar{
modules.export = bar;

And then in app.js I have

var foo = require('./foo');
var fooClass = new bar();

But it throws an error saying
is undefined. What am I doing wrong here?

Answer Source

Use module.exports, not modules.export.

Also check how you're importing. When you use var foo = require('./foo');, you must also use var fooClass = new foo(). The local variable / class will match the name you gave it when you required it, not the name you gave it when you defined it in the original file.

For example, the following would also work:

var Bar = require('./foo');
var bar = new Bar();

You can label your variables whatever you want when you import / require them, regardless of their names when you declare them -- including classes.

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