Dead Horse's Blog

Node.js net 模块阅读笔记

2012-08-26

引用node源码中的C模块

// constructor for lazy loading
function createPipe() {
  var Pipe = process.binding('pipe_wrap').Pipe;
  return new Pipe();
}

通过与或操作设置读取标记位

/* Bit flags for socket._flags */
var FLAG_GOT_EOF = 1 << 0;
var FLAG_SHUTDOWN = 1 << 1;
var FLAG_DESTROY_SOON = 1 << 2;
var FLAG_SHUTDOWN_QUEUED = 1 << 3;

var flags = 0;
flags & FLAG_GOT_EOF; //检查是否设置了这个标识
flags | FLAG_GOT_EOF; //设置标志位

字符串与整数的转换

var secs = ~~(msecs / 1000);

转换对象为Boolean

var bool = !!input;

process.nextTick的使用

有些情况下,可能希望在执行完当前事件循环之后再执行一些操作,通过process.nextTick将操作放到下一个事件循环去做,这样这些操作将不会影响当前事件循环的其他操作。

//in socket.onread, when meet `EOF` 
// We call destroy() before end(). 'close' not emitted until nextTick so
// the 'end' event will come first as required.
if (!self.writable) self._destroy();

if (!self.allowHalfOpen) self.end();
if (self._events && self._events['end']) self.emit('end');

//in self_destroy
process.nextTick(function() {
  self.emit('close', exception ? true : false);
});

通过process.nextTick(),可以保证在调用_destroy的时候不会先触发close事件。

格式化输入参数,重新调用自身

Socket.prototype.connect = function(options, cb) {
  if (typeof options !== 'object') {
    var args = normalizeConnectArgs(arguments);
    return Socket.prototype.connect.apply(this, args);
  }
  // do something
}
blog comments powered by Disqus