I tried to sort the inclusion of other js files in node.js.
I read all about the require function and other alternatives and decided to go with the require function (since the code will only be used in node.js, not in the browser).
In my code, I use prototypes to create an โobjectโ that I want to instantiate later.
To make it work, I write the code as follows (let's 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 (let's 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 everything works fine, but I do not have a good understanding of what is happening.
My main problem is using 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 the like, but I couldn't get it to work.
I have to use export, and if so, why?
Please note that I used the AR Drone project as an example, the above code is based on how they made their modules inside. Refer to Client.js and index.js .