1

私は最初の「本格的な」node.jsモジュールを書いています.いくつかのアドバイス/ベストプラクティスが必要です...

質問はコード内のコメントを読んでください!

サーバー.js

var Client = require('./index');
var client = Client.createClient();

client.on('data', function(data) {
  console.log(data);
});

client.on('ERROR', function(data) {
  console.log(data);
});

node-module.js

exports.Client = require('./Client');

exports.createClient = function(options) {
  return new exports.Client(options);
};

/**
 * Question 1:
 * I want to have an optional WebUI for this, how should it recieve the data?
 * I figured via event-emitters is best(?)
 * But where should it be placed (and how) so it can access the events from Client.js?
 */
exports.createServer = function(options) {
  //...
}

クライアント.js

Client.Handlers = require('./Handlers');
module.exports = Client;

function Client(options) {
  // ...

this._callback_handlers['ERROR'] = Client.Handlers.error

  /**
   * Question 2:
   * Initialize connection to server
   *
   * Should it be something like this instead:
   * this._socket = this.Connect(options); ?
   * How do I achieve this?
   * And at the same time keeping the buffer-variable local to the Connect function?
   */
  this.Connect();
});

Client.prototype.Connect = function() {
  var self = this;
  var buffer = '';
  this._socket = net.connect({
    host: self.options.host,
    port: self.options.port
  }, function() {

  })
  .on('data', function(chunk) {
    var offset, part;
    buffer += chunk;

/**
 * Question 3:
 * Buffer up and parse only whole rows
 * 
 * This is a OK way to do it, right?
 * Should I listen for the event "data"
 * instead of calling self.parse_response() like a normal function?
 *
 */
while((offset = buffer.indexOf("\n")) > -1) {
  part = buffer.substr(0, offset);
  buffer = buffer.substr(offset + 1);


      if(part) {
        self.emit('data', part);
        self.parse_response(part);
      }
    }
  })
};


Client.prototype.parse_response = function(data) {

  // ...

  /**
   * Question 4:
   * Send callbacks
   *
   * _callback_handlers is an array containing callbacks functions
   * (see top of Client.js: this._callback_handlers['ERROR'] = Client.Handlers.error)
   * 
   * I would perfer to use something like this instead:
   *   this.emit(data[0], data[1]);
   *
   * But how do I make Handlers.js listen to these events?
   * since "Client" dosent exist there
   *
   * The reason I have handlers.js in the first place
   * is to give the code a better structure
   *   
   */

  if(this._callback_handlers[data[0]]) {
    this._callback_handlers[data[0]].apply(this, data[1]);
  }

}

Handlers.js

//...
exports.error = function(a) {
  this.emit('ERROR', a);
}
//...
4

0 に答える 0