Require() wrapper in node.js?

Tag: node.js Author: raidonwong Date: 2010-09-15

I try to include a .js file in my app with node require(), but get this error. Any idea?

a.js :

function a() {
  this.a = 'a';
}

Node application :

require("./a.js");
var test = new a();

Error:

/Users/.../app.js:14
var test = new a()
^
ReferenceError: a is not defined

Best Answer

Read about commonjs modules here (or just follow examples below): http://wiki.commonjs.org/wiki/Modules/1.0

a.js should be:

function a() {
  this.a = 'a';
}

exports.a = a; //this exports a

your app should be:

var everything_in_module_a = require('./a.js');
var a = everything_in_module_a.a;
var test = new a();

or your app could be:

var a = require('./a.js').a;
var test = new a();