Metalskin Metalskin - 2 months ago 20
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) {
EventEmitter.call(this);
options = options || {};
...
}

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

Vehicle.prototype.testRun = function() {
this._doStartEvent();
};


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: "192.168.1.3"});

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

remoteVehicle.testRun();


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
and
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

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: "192.168.1.3"});

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

remoteVehicle.testRun();
Comments