Metalskin Metalskin - 1 year ago 93
Javascript Question

Node js and new when using require

I've been trying to sort out the include of other js files within node.js.

I've read all about the require function and other alternatives and decided to go with the require function (as the code will only ever be used on node.js, not in a browser).

In my code I'm using prototypes to create an 'object' which I later wish to create an instance off.

To get it to work I've been writing code like the following (lets call it vehicle.js):

var util = require('util');
var EventEmitter = require('events').EventEmitter;

module.exports = Vehicle;

util.inherits(Vehicle, EventEmitter);

function Vehicle(options) {;
options = options || {};

Vehicle.prototype._doStartEvent = function(data) {
this.emit('start', data);

Vehicle.prototype.testRun = function() {

Then in my main js (lets call it server.js), I have the following:

var test = exports;
exports.Vehicle = require('./vehicle.js');

var remoteVehicle = new test.Vehicle({address: ""});

remoteVehicle.on('start', function(d) {console.log('started');});


Now this all works fine, but I do not have a good understanding of what is going on.

My main concern is the use of
var test = exports;
and then
exports.Vehicle = require(...)

I tried just doing something like
var vehicle = require(...).Vehicle
var vehicle = require(...)
, with the goal of just using
new Vehicle
or similar, but I couldn't get it to work.

Am I forced to use exports and if so why?

Please note I've been using the AR Drone project as an example, the above code is based on how they have done their modules internally. Refer to Client.js and index.js.

Answer Source

result of require is a reference to exports object which is function in your case. Just assign to a variable with the same name as class (or any other) and use as a parameter to new

var Vehicle = require('./vehicle.js');

var remoteVehicle = new Vehicle({address: ""});

remoteVehicle.on('start', function(d) {console.log('started');});

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