Browse Source

lib: macro-ify type checks

Increases the grep factor. Makes it easier to harmonize type checks
across the code base.
v0.11.5-release
Ben Noordhuis 12 years ago
parent
commit
0330bdf519
  1. 21
      lib/_debugger.js
  2. 2
      lib/_http_agent.js
  3. 10
      lib/_http_client.js
  4. 8
      lib/_http_incoming.js
  5. 16
      lib/_http_outgoing.js
  6. 10
      lib/_http_server.js
  7. 22
      lib/_stream_readable.js
  8. 6
      lib/_stream_transform.js
  9. 25
      lib/_stream_writable.js
  10. 14
      lib/_tls_legacy.js
  11. 18
      lib/_tls_wrap.js
  12. 24
      lib/assert.js
  13. 58
      lib/buffer.js
  14. 46
      lib/child_process.js
  15. 20
      lib/cluster.js
  16. 2
      lib/console.js
  17. 10
      lib/crypto.js
  18. 18
      lib/dgram.js
  19. 6
      lib/dns.js
  20. 2
      lib/domain.js
  21. 37
      lib/events.js
  22. 145
      lib/fs.js
  23. 12
      lib/https.js
  24. 2
      lib/module.js
  25. 66
      lib/net.js
  26. 10
      lib/path.js
  27. 32
      lib/querystring.js
  28. 24
      lib/readline.js
  29. 28
      lib/repl.js
  30. 6
      lib/smalloc.js
  31. 2
      lib/stream.js
  32. 8
      lib/tls.js
  33. 17
      lib/url.js
  34. 71
      lib/util.js
  35. 2
      lib/vm.js
  36. 24
      lib/zlib.js
  37. 1
      node.gyp
  38. 16
      src/macros.py

21
lib/_debugger.js

@ -182,7 +182,7 @@ exports.Client = Client;
Client.prototype._addHandle = function(desc) { Client.prototype._addHandle = function(desc) {
if (typeof desc != 'object' || typeof desc.handle != 'number') { if (!IS_OBJECT(desc) || !IS_NUMBER(desc.handle)) {
return; return;
} }
@ -296,7 +296,7 @@ Client.prototype.reqLookup = function(refs, cb) {
this.req(req, function(err, res) { this.req(req, function(err, res) {
if (err) return cb(err); if (err) return cb(err);
for (var ref in res) { for (var ref in res) {
if (typeof res[ref] == 'object') { if (IS_OBJECT(res[ref])) {
self._addHandle(res[ref]); self._addHandle(res[ref]);
} }
} }
@ -559,8 +559,7 @@ Client.prototype.mirrorObject = function(handle, depth, cb) {
} }
if (Array.isArray(mirror) && if (IS_ARRAY(mirror) && !IS_NUMBER(prop.name)) {
typeof prop.name != 'number') {
// Skip the 'length' property. // Skip the 'length' property.
return; return;
} }
@ -593,7 +592,7 @@ Client.prototype.mirrorObject = function(handle, depth, cb) {
val = function() {}; val = function() {};
} else if (handle.type === 'null') { } else if (handle.type === 'null') {
val = null; val = null;
} else if (handle.value !== undefined) { } else if (!IS_UNDEFINED(handle.value)) {
val = handle.value; val = handle.value;
} else if (handle.type === 'undefined') { } else if (handle.type === 'undefined') {
val = undefined; val = undefined;
@ -892,7 +891,7 @@ Interface.prototype.print = function(text, oneline) {
if (this.killed) return; if (this.killed) return;
this.clearline(); this.clearline();
this.stdout.write(typeof text === 'string' ? text : util.inspect(text)); this.stdout.write(IS_STRING(text) ? text : util.inspect(text));
if (oneline !== true) { if (oneline !== true) {
this.stdout.write('\n'); this.stdout.write('\n');
@ -1214,7 +1213,7 @@ Interface.prototype.scripts = function() {
this.pause(); this.pause();
for (var id in client.scripts) { for (var id in client.scripts) {
var script = client.scripts[id]; var script = client.scripts[id];
if (typeof script == 'object' && script.name) { if (IS_OBJECT(script) && script.name) {
if (displayNatives || if (displayNatives ||
script.name == client.currentScript || script.name == client.currentScript ||
!script.isNative) { !script.isNative) {
@ -1351,13 +1350,13 @@ Interface.prototype.setBreakpoint = function(script, line,
ambiguous; ambiguous;
// setBreakpoint() should insert breakpoint on current line // setBreakpoint() should insert breakpoint on current line
if (script === undefined) { if (IS_UNDEFINED(script)) {
script = this.client.currentScript; script = this.client.currentScript;
line = this.client.currentSourceLine + 1; line = this.client.currentSourceLine + 1;
} }
// setBreakpoint(line-number) should insert breakpoint in current script // setBreakpoint(line-number) should insert breakpoint in current script
if (line === undefined && typeof script === 'number') { if (IS_UNDEFINED(line) && IS_NUMBER(script)) {
line = script; line = script;
script = this.client.currentScript; script = this.client.currentScript;
} }
@ -1452,7 +1451,7 @@ Interface.prototype.clearBreakpoint = function(script, line) {
if (bp.scriptId === script || if (bp.scriptId === script ||
bp.scriptReq === script || bp.scriptReq === script ||
(bp.script && bp.script.indexOf(script) !== -1)) { (bp.script && bp.script.indexOf(script) !== -1)) {
if (index !== undefined) { if (!IS_UNDEFINED(index)) {
ambiguous = true; ambiguous = true;
} }
if (bp.line === line) { if (bp.line === line) {
@ -1465,7 +1464,7 @@ Interface.prototype.clearBreakpoint = function(script, line) {
if (ambiguous) return this.error('Script name is ambiguous'); if (ambiguous) return this.error('Script name is ambiguous');
if (breakpoint === undefined) { if (IS_UNDEFINED(breakpoint)) {
return this.error('Script : ' + script + ' not found'); return this.error('Script : ' + script + ' not found');
} }

2
lib/_http_agent.js

@ -246,7 +246,7 @@ Agent.prototype.destroy = function() {
}; };
Agent.prototype.request = function(options, cb) { Agent.prototype.request = function(options, cb) {
if (typeof options === 'string') { if (IS_STRING(options)) {
options = url.parse(options); options = url.parse(options);
} }
// don't try to do dns lookups of foo.com:8080, just foo.com // don't try to do dns lookups of foo.com:8080, just foo.com

10
lib/_http_client.js

@ -44,14 +44,14 @@ function ClientRequest(options, cb) {
var self = this; var self = this;
OutgoingMessage.call(self); OutgoingMessage.call(self);
self.agent = options.agent === undefined ? globalAgent : options.agent; self.agent = IS_UNDEFINED(options.agent) ? globalAgent : options.agent;
var defaultPort = options.defaultPort || 80; var defaultPort = options.defaultPort || 80;
var port = options.port || defaultPort; var port = options.port || defaultPort;
var host = options.hostname || options.host || 'localhost'; var host = options.hostname || options.host || 'localhost';
if (options.setHost === undefined) { if (IS_UNDEFINED(options.setHost)) {
var setHost = true; var setHost = true;
} }
@ -63,7 +63,7 @@ function ClientRequest(options, cb) {
self.once('response', cb); self.once('response', cb);
} }
if (!Array.isArray(options.headers)) { if (!IS_ARRAY(options.headers)) {
if (options.headers) { if (options.headers) {
var keys = Object.keys(options.headers); var keys = Object.keys(options.headers);
for (var i = 0, l = keys.length; i < l; i++) { for (var i = 0, l = keys.length; i < l; i++) {
@ -92,7 +92,7 @@ function ClientRequest(options, cb) {
self.useChunkedEncodingByDefault = true; self.useChunkedEncodingByDefault = true;
} }
if (Array.isArray(options.headers)) { if (IS_ARRAY(options.headers)) {
self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n', self._storeHeader(self.method + ' ' + self.path + ' HTTP/1.1\r\n',
options.headers); options.headers);
} else if (self.getHeader('expect')) { } else if (self.getHeader('expect')) {
@ -413,7 +413,7 @@ ClientRequest.prototype.onSocket = function(socket) {
httpSocketSetup(socket); httpSocketSetup(socket);
// Propagate headers limit from request object to parser // Propagate headers limit from request object to parser
if (typeof req.maxHeadersCount === 'number') { if (IS_NUMBER(req.maxHeadersCount)) {
parser.maxHeaderPairs = req.maxHeadersCount << 1; parser.maxHeaderPairs = req.maxHeadersCount << 1;
} else { } else {
// Set default value because parser may be reused from FreeList // Set default value because parser may be reused from FreeList

8
lib/_http_incoming.js

@ -125,7 +125,7 @@ IncomingMessage.prototype._addHeaderLine = function(field, value) {
switch (field) { switch (field) {
// Array headers: // Array headers:
case 'set-cookie': case 'set-cookie':
if (dest[field] !== undefined) { if (!IS_UNDEFINED(dest[field])) {
dest[field].push(value); dest[field].push(value);
} else { } else {
dest[field] = [value]; dest[field] = [value];
@ -145,7 +145,7 @@ IncomingMessage.prototype._addHeaderLine = function(field, value) {
case 'proxy-authenticate': case 'proxy-authenticate':
case 'sec-websocket-extensions': case 'sec-websocket-extensions':
case 'sec-websocket-protocol': case 'sec-websocket-protocol':
if (dest[field] !== undefined) { if (!IS_UNDEFINED(dest[field])) {
dest[field] += ', ' + value; dest[field] += ', ' + value;
} else { } else {
dest[field] = value; dest[field] = value;
@ -156,14 +156,14 @@ IncomingMessage.prototype._addHeaderLine = function(field, value) {
default: default:
if (field.slice(0, 2) == 'x-') { if (field.slice(0, 2) == 'x-') {
// except for x- // except for x-
if (dest[field] !== undefined) { if (!IS_UNDEFINED(dest[field])) {
dest[field] += ', ' + value; dest[field] += ', ' + value;
} else { } else {
dest[field] = value; dest[field] = value;
} }
} else { } else {
// drop duplicates // drop duplicates
if (dest[field] === undefined) dest[field] = value; if (IS_UNDEFINED(dest[field])) dest[field] = value;
} }
break; break;
} }

16
lib/_http_outgoing.js

@ -115,7 +115,7 @@ OutgoingMessage.prototype._send = function(data, encoding) {
// the same packet. Future versions of Node are going to take care of // the same packet. Future versions of Node are going to take care of
// this at a lower level and in a more general way. // this at a lower level and in a more general way.
if (!this._headerSent) { if (!this._headerSent) {
if (typeof data === 'string') { if (IS_STRING(data)) {
data = this._header + data; data = this._header + data;
} else { } else {
this.output.unshift(this._header); this.output.unshift(this._header);
@ -166,7 +166,7 @@ OutgoingMessage.prototype._buffer = function(data, encoding) {
var length = this.output.length; var length = this.output.length;
if (length === 0 || typeof data != 'string') { if (length === 0 || !IS_STRING(data)) {
this.output.push(data); this.output.push(data);
this.outputEncodings.push(encoding); this.outputEncodings.push(encoding);
return false; return false;
@ -205,7 +205,7 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
if (headers) { if (headers) {
var keys = Object.keys(headers); var keys = Object.keys(headers);
var isArray = (Array.isArray(headers)); var isArray = IS_ARRAY(headers);
var field, value; var field, value;
for (var i = 0, l = keys.length; i < l; i++) { for (var i = 0, l = keys.length; i < l; i++) {
@ -218,7 +218,7 @@ OutgoingMessage.prototype._storeHeader = function(firstLine, headers) {
value = headers[key]; value = headers[key];
} }
if (Array.isArray(value)) { if (IS_ARRAY(value)) {
for (var j = 0; j < value.length; j++) { for (var j = 0; j < value.length; j++) {
storeHeader(this, state, field, value[j]); storeHeader(this, state, field, value[j]);
} }
@ -401,7 +401,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding) {
return true; return true;
} }
if (typeof chunk !== 'string' && !Buffer.isBuffer(chunk)) { if (!IS_STRING(chunk) && !IS_BUFFER(chunk)) {
throw new TypeError('first argument must be a string or Buffer'); throw new TypeError('first argument must be a string or Buffer');
} }
@ -412,7 +412,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding) {
var len, ret; var len, ret;
if (this.chunkedEncoding) { if (this.chunkedEncoding) {
if (typeof(chunk) === 'string' && if (IS_STRING(chunk) &&
encoding !== 'hex' && encoding !== 'hex' &&
encoding !== 'base64' && encoding !== 'base64' &&
encoding !== 'binary') { encoding !== 'binary') {
@ -444,7 +444,7 @@ OutgoingMessage.prototype.write = function(chunk, encoding) {
OutgoingMessage.prototype.addTrailers = function(headers) { OutgoingMessage.prototype.addTrailers = function(headers) {
this._trailer = ''; this._trailer = '';
var keys = Object.keys(headers); var keys = Object.keys(headers);
var isArray = (Array.isArray(headers)); var isArray = IS_ARRAY(headers);
var field, value; var field, value;
for (var i = 0, l = keys.length; i < l; i++) { for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i]; var key = keys[i];
@ -466,7 +466,7 @@ var crlf_buf = new Buffer('\r\n');
OutgoingMessage.prototype.end = function(data, encoding) { OutgoingMessage.prototype.end = function(data, encoding) {
if (data && typeof data !== 'string' && !Buffer.isBuffer(data)) { if (data && !IS_STRING(data) && !IS_BUFFER(data)) {
throw new TypeError('first argument must be a string or Buffer'); throw new TypeError('first argument must be a string or Buffer');
} }

10
lib/_http_server.js

@ -173,7 +173,7 @@ ServerResponse.prototype._implicitHeader = function() {
ServerResponse.prototype.writeHead = function(statusCode) { ServerResponse.prototype.writeHead = function(statusCode) {
var reasonPhrase, headers, headerIndex; var reasonPhrase, headers, headerIndex;
if (typeof arguments[1] == 'string') { if (IS_STRING(arguments[1])) {
reasonPhrase = arguments[1]; reasonPhrase = arguments[1];
headerIndex = 2; headerIndex = 2;
} else { } else {
@ -188,13 +188,13 @@ ServerResponse.prototype.writeHead = function(statusCode) {
// Slow-case: when progressive API and header fields are passed. // Slow-case: when progressive API and header fields are passed.
headers = this._renderHeaders(); headers = this._renderHeaders();
if (Array.isArray(obj)) { if (IS_ARRAY(obj)) {
// handle array case // handle array case
// TODO: remove when array is no longer accepted // TODO: remove when array is no longer accepted
var field; var field;
for (var i = 0, len = obj.length; i < len; ++i) { for (var i = 0, len = obj.length; i < len; ++i) {
field = obj[i][0]; field = obj[i][0];
if (headers[field] !== undefined) { if (!IS_UNDEFINED(headers[field])) {
obj.push([field, headers[field]]); obj.push([field, headers[field]]);
} }
} }
@ -332,7 +332,7 @@ function connectionListener(socket) {
parser.incoming = null; parser.incoming = null;
// Propagate headers limit from server instance to parser // Propagate headers limit from server instance to parser
if (typeof this.maxHeadersCount === 'number') { if (IS_NUMBER(this.maxHeadersCount)) {
parser.maxHeaderPairs = this.maxHeadersCount << 1; parser.maxHeaderPairs = this.maxHeadersCount << 1;
} else { } else {
// Set default value because parser may be reused from FreeList // Set default value because parser may be reused from FreeList
@ -442,7 +442,7 @@ function connectionListener(socket) {
} }
}); });
if (req.headers.expect !== undefined && if (!IS_UNDEFINED(req.headers.expect) &&
(req.httpVersionMajor == 1 && req.httpVersionMinor == 1) && (req.httpVersionMajor == 1 && req.httpVersionMinor == 1) &&
continueExpression.test(req.headers['expect'])) { continueExpression.test(req.headers['expect'])) {
res._expect_continue = true; res._expect_continue = true;

22
lib/_stream_readable.js

@ -117,7 +117,7 @@ function Readable(options) {
Readable.prototype.push = function(chunk, encoding) { Readable.prototype.push = function(chunk, encoding) {
var state = this._readableState; var state = this._readableState;
if (typeof chunk === 'string' && !state.objectMode) { if (IS_STRING(chunk) && !state.objectMode) {
encoding = encoding || state.defaultEncoding; encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) { if (encoding !== state.encoding) {
chunk = new Buffer(chunk, encoding); chunk = new Buffer(chunk, encoding);
@ -138,7 +138,7 @@ function readableAddChunk(stream, state, chunk, encoding, addToFront) {
var er = chunkInvalid(state, chunk); var er = chunkInvalid(state, chunk);
if (er) { if (er) {
stream.emit('error', er); stream.emit('error', er);
} else if (chunk === null || chunk === undefined) { } else if (IS_NULL_OR_UNDEFINED(chunk)) {
state.reading = false; state.reading = false;
if (!state.ended) if (!state.ended)
onEofChunk(stream, state); onEofChunk(stream, state);
@ -219,7 +219,7 @@ function howMuchToRead(n, state) {
if (state.objectMode) if (state.objectMode)
return n === 0 ? 0 : 1; return n === 0 ? 0 : 1;
if (isNaN(n) || n === null) { if (isNaN(n) || IS_NULL(n)) {
// only flow one buffer at a time // only flow one buffer at a time
if (state.flowing && state.buffer.length) if (state.flowing && state.buffer.length)
return state.buffer[0].length; return state.buffer[0].length;
@ -256,7 +256,7 @@ Readable.prototype.read = function(n) {
state.calledRead = true; state.calledRead = true;
var nOrig = n; var nOrig = n;
if (typeof n !== 'number' || n > 0) if (!IS_NUMBER(n) || n > 0)
state.emittedReadable = false; state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we // if we're doing read(0) to trigger a readable event, but we
@ -345,7 +345,7 @@ Readable.prototype.read = function(n) {
else else
ret = null; ret = null;
if (ret === null) { if (IS_NULL(ret)) {
state.needReadable = true; state.needReadable = true;
n = 0; n = 0;
} }
@ -363,17 +363,16 @@ Readable.prototype.read = function(n) {
if (state.ended && !state.endEmitted && state.length === 0) if (state.ended && !state.endEmitted && state.length === 0)
endReadable(this); endReadable(this);
if (ret !== null) if (!IS_NULL(ret))
this.emit('data', ret); this.emit('data', ret);
return ret; return ret;
}; };
function chunkInvalid(state, chunk) { function chunkInvalid(state, chunk) {
var er = null; var er = null;
if (!Buffer.isBuffer(chunk) && if (!IS_BUFFER(chunk) &&
'string' !== typeof chunk && !IS_STRING(chunk) &&
chunk !== null && !IS_NULL_OR_UNDEFINED(chunk) &&
chunk !== undefined &&
!state.objectMode && !state.objectMode &&
!er) { !er) {
er = new TypeError('Invalid non-string/buffer chunk'); er = new TypeError('Invalid non-string/buffer chunk');
@ -775,8 +774,7 @@ Readable.prototype.wrap = function(stream) {
// proxy all the other methods. // proxy all the other methods.
// important when wrapping filters and duplexes. // important when wrapping filters and duplexes.
for (var i in stream) { for (var i in stream) {
if (typeof stream[i] === 'function' && if (IS_FUNCTION(stream[i]) && IS_UNDEFINED(this[i])) {
typeof this[i] === 'undefined') {
this[i] = function(method) { return function() { this[i] = function(method) { return function() {
return stream[method].apply(stream, arguments); return stream[method].apply(stream, arguments);
}}(i); }}(i);

6
lib/_stream_transform.js

@ -92,7 +92,7 @@ function afterTransform(stream, er, data) {
ts.writechunk = null; ts.writechunk = null;
ts.writecb = null; ts.writecb = null;
if (data !== null && data !== undefined) if (!IS_NULL_OR_UNDEFINED(data))
stream.push(data); stream.push(data);
if (cb) if (cb)
@ -126,7 +126,7 @@ function Transform(options) {
this._readableState.sync = false; this._readableState.sync = false;
this.once('prefinish', function() { this.once('prefinish', function() {
if ('function' === typeof this._flush) if (IS_FUNCTION(this._flush))
this._flush(function(er) { this._flush(function(er) {
done(stream, er); done(stream, er);
}); });
@ -174,7 +174,7 @@ Transform.prototype._write = function(chunk, encoding, cb) {
Transform.prototype._read = function(n) { Transform.prototype._read = function(n) {
var ts = this._transformState; var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) { if (!IS_NULL(ts.writechunk) && ts.writecb && !ts.transforming) {
ts.transforming = true; ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else { } else {

25
lib/_stream_writable.js

@ -153,10 +153,9 @@ function writeAfterEnd(stream, state, cb) {
// how many bytes or characters. // how many bytes or characters.
function validChunk(stream, state, chunk, cb) { function validChunk(stream, state, chunk, cb) {
var valid = true; var valid = true;
if (!Buffer.isBuffer(chunk) && if (!IS_BUFFER(chunk) &&
'string' !== typeof chunk && !IS_STRING(chunk) &&
chunk !== null && !IS_NULL_OR_UNDEFINED(chunk) &&
chunk !== undefined &&
!state.objectMode) { !state.objectMode) {
var er = new TypeError('Invalid non-string/buffer chunk'); var er = new TypeError('Invalid non-string/buffer chunk');
stream.emit('error', er); stream.emit('error', er);
@ -172,17 +171,17 @@ Writable.prototype.write = function(chunk, encoding, cb) {
var state = this._writableState; var state = this._writableState;
var ret = false; var ret = false;
if (typeof encoding === 'function') { if (IS_FUNCTION(encoding)) {
cb = encoding; cb = encoding;
encoding = null; encoding = null;
} }
if (Buffer.isBuffer(chunk)) if (IS_BUFFER(chunk))
encoding = 'buffer'; encoding = 'buffer';
else if (!encoding) else if (!encoding)
encoding = state.defaultEncoding; encoding = state.defaultEncoding;
if (typeof cb !== 'function') if (!IS_FUNCTION(cb))
cb = function() {}; cb = function() {};
if (state.ended) if (state.ended)
@ -217,9 +216,7 @@ Writable.prototype.uncork = function() {
}; };
function decodeChunk(state, chunk, encoding) { function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && if (!state.objectMode && state.decodeStrings !== false && IS_STRING(chunk)) {
state.decodeStrings !== false &&
typeof chunk === 'string') {
chunk = new Buffer(chunk, encoding); chunk = new Buffer(chunk, encoding);
} }
return chunk; return chunk;
@ -230,7 +227,7 @@ function decodeChunk(state, chunk, encoding) {
// If we return false, then we need a drain event, so set that flag. // If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) { function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding); chunk = decodeChunk(state, chunk, encoding);
if (Buffer.isBuffer(chunk)) if (IS_BUFFER(chunk))
encoding = 'buffer'; encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length; var len = state.objectMode ? 1 : chunk.length;
@ -391,16 +388,16 @@ Writable.prototype._writev = null;
Writable.prototype.end = function(chunk, encoding, cb) { Writable.prototype.end = function(chunk, encoding, cb) {
var state = this._writableState; var state = this._writableState;
if (typeof chunk === 'function') { if (IS_FUNCTION(chunk)) {
cb = chunk; cb = chunk;
chunk = null; chunk = null;
encoding = null; encoding = null;
} else if (typeof encoding === 'function') { } else if (IS_FUNCTION(encoding)) {
cb = encoding; cb = encoding;
encoding = null; encoding = null;
} }
if (typeof chunk !== 'undefined' && chunk !== null) if (!IS_NULL_OR_UNDEFINED(chunk))
this.write(chunk, encoding); this.write(chunk, encoding);
// .end() fully uncorks // .end() fully uncorks

14
lib/_tls_legacy.js

@ -36,7 +36,7 @@ SlabBuffer.prototype.use = function use(context, fn, size) {
var actualSize = this.remaining; var actualSize = this.remaining;
if (size !== null) actualSize = Math.min(size, actualSize); if (!IS_NULL(size)) actualSize = Math.min(size, actualSize);
var bytes = fn.call(context, this.pool, this.offset, actualSize); var bytes = fn.call(context, this.pool, this.offset, actualSize);
if (bytes > 0) { if (bytes > 0) {
@ -72,7 +72,7 @@ function CryptoStream(pair, options) {
this._finished = false; this._finished = false;
this._opposite = null; this._opposite = null;
if (slabBuffer === null) slabBuffer = new SlabBuffer(); if (IS_NULL(slabBuffer)) slabBuffer = new SlabBuffer();
this._buffer = slabBuffer; this._buffer = slabBuffer;
this.once('finish', onCryptoStreamFinish); this.once('finish', onCryptoStreamFinish);
@ -144,7 +144,7 @@ CryptoStream.prototype.init = function init() {
CryptoStream.prototype._write = function write(data, encoding, cb) { CryptoStream.prototype._write = function write(data, encoding, cb) {
assert(this._pending === null); assert(IS_NULL(this._pending));
// Black-hole data // Black-hole data
if (!this.pair.ssl) return cb(null); if (!this.pair.ssl) return cb(null);
@ -191,7 +191,7 @@ CryptoStream.prototype._write = function write(data, encoding, cb) {
// Invoke callback only when all data read from opposite stream // Invoke callback only when all data read from opposite stream
if (this._opposite._halfRead) { if (this._opposite._halfRead) {
assert(this._sslOutCb === null); assert(IS_NULL(this._sslOutCb));
this._sslOutCb = cb; this._sslOutCb = cb;
} else { } else {
cb(null); cb(null);
@ -285,8 +285,8 @@ CryptoStream.prototype._read = function read(size) {
} }
// Try writing pending data // Try writing pending data
if (this._pending !== null) this._writePending(); if (!IS_NULL(this._pending)) this._writePending();
if (this._opposite._pending !== null) this._opposite._writePending(); if (!IS_NULL(this._opposite._pending)) this._opposite._writePending();
if (bytesRead === 0) { if (bytesRead === 0) {
// EOF when cleartext has finished and we have nothing to read // EOF when cleartext has finished and we have nothing to read
@ -405,7 +405,7 @@ CryptoStream.prototype.end = function(chunk, encoding) {
} }
// Write pending data first // Write pending data first
if (this._pending !== null) this._writePending(); if (!IS_NULL(this._pending)) this._writePending();
this.writable = false; this.writable = false;

18
lib/_tls_wrap.js

@ -207,7 +207,7 @@ TLSSocket.prototype.setServername = function(name) {
}; };
TLSSocket.prototype.setSession = function(session) { TLSSocket.prototype.setSession = function(session) {
if (typeof session === 'string') if (IS_STRING(session))
session = new Buffer(session, 'binary'); session = new Buffer(session, 'binary');
this.ssl.setSession(session); this.ssl.setSession(session);
}; };
@ -319,10 +319,10 @@ TLSSocket.prototype.getCipher = function(err) {
// //
function Server(/* [options], listener */) { function Server(/* [options], listener */) {
var options, listener; var options, listener;
if (typeof arguments[0] == 'object') { if (IS_OBJECT(arguments[0])) {
options = arguments[0]; options = arguments[0];
listener = arguments[1]; listener = arguments[1];
} else if (typeof arguments[0] == 'function') { } else if (IS_FUNCTION(arguments[0])) {
options = {}; options = {};
listener = arguments[0]; listener = arguments[0];
} }
@ -355,7 +355,7 @@ function Server(/* [options], listener */) {
var timeout = options.handshakeTimeout || (120 * 1000); var timeout = options.handshakeTimeout || (120 * 1000);
if (typeof timeout !== 'number') { if (!IS_NUMBER(timeout)) {
throw new TypeError('handshakeTimeout must be a number'); throw new TypeError('handshakeTimeout must be a number');
} }
@ -423,13 +423,13 @@ exports.createServer = function(options, listener) {
Server.prototype.setOptions = function(options) { Server.prototype.setOptions = function(options) {
if (typeof options.requestCert == 'boolean') { if (IS_BOOLEAN(options.requestCert)) {
this.requestCert = options.requestCert; this.requestCert = options.requestCert;
} else { } else {
this.requestCert = false; this.requestCert = false;
} }
if (typeof options.rejectUnauthorized == 'boolean') { if (IS_BOOLEAN(options.rejectUnauthorized)) {
this.rejectUnauthorized = options.rejectUnauthorized; this.rejectUnauthorized = options.rejectUnauthorized;
} else { } else {
this.rejectUnauthorized = false; this.rejectUnauthorized = false;
@ -481,7 +481,7 @@ Server.prototype.SNICallback = function(servername) {
var ctx; var ctx;
this._contexts.some(function(elem) { this._contexts.some(function(elem) {
if (servername.match(elem[0]) !== null) { if (!IS_NULL(servername.match(elem[0]))) {
ctx = elem[1]; ctx = elem[1];
return true; return true;
} }
@ -510,9 +510,9 @@ function normalizeConnectArgs(listArgs) {
var options = args[0]; var options = args[0];
var cb = args[1]; var cb = args[1];
if (typeof listArgs[1] === 'object') { if (IS_OBJECT(listArgs[1])) {
options = util._extend(options, listArgs[1]); options = util._extend(options, listArgs[1]);
} else if (typeof listArgs[2] === 'object') { } else if (IS_OBJECT(listArgs[2])) {
options = util._extend(options, listArgs[2]); options = util._extend(options, listArgs[2]);
} }

24
lib/assert.js

@ -51,20 +51,20 @@ assert.AssertionError = function AssertionError(options) {
util.inherits(assert.AssertionError, Error); util.inherits(assert.AssertionError, Error);
function replacer(key, value) { function replacer(key, value) {
if (value === undefined) { if (IS_UNDEFINED(value)) {
return '' + value; return '' + value;
} }
if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) { if (IS_NUMBER(value) && (isNaN(value) || !isFinite(value))) {
return value.toString(); return value.toString();
} }
if (typeof value === 'function' || value instanceof RegExp) { if (IS_FUNCTION(value) || IS_REGEXP(value)) {
return value.toString(); return value.toString();
} }
return value; return value;
} }
function truncate(s, n) { function truncate(s, n) {
if (typeof s == 'string') { if (IS_STRING(s)) {
return s.length < n ? s : s.slice(0, n); return s.length < n ? s : s.slice(0, n);
} else { } else {
return s; return s;
@ -144,7 +144,7 @@ function _deepEqual(actual, expected) {
if (actual === expected) { if (actual === expected) {
return true; return true;
} else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) { } else if (IS_BUFFER(actual) && IS_BUFFER(expected)) {
if (actual.length != expected.length) return false; if (actual.length != expected.length) return false;
for (var i = 0; i < actual.length; i++) { for (var i = 0; i < actual.length; i++) {
@ -155,13 +155,13 @@ function _deepEqual(actual, expected) {
// 7.2. If the expected value is a Date object, the actual value is // 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time. // equivalent if it is also a Date object that refers to the same time.
} else if (actual instanceof Date && expected instanceof Date) { } else if (IS_DATE(actual) && IS_DATE(expected)) {
return actual.getTime() === expected.getTime(); return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is // 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and // equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (actual instanceof RegExp && expected instanceof RegExp) { } else if (IS_REGEXP(actual) && IS_REGEXP(expected)) {
return actual.source === expected.source && return actual.source === expected.source &&
actual.global === expected.global && actual.global === expected.global &&
actual.multiline === expected.multiline && actual.multiline === expected.multiline &&
@ -170,7 +170,7 @@ function _deepEqual(actual, expected) {
// 7.4. Other pairs that do not both pass typeof value == 'object', // 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==. // equivalence is determined by ==.
} else if (typeof actual != 'object' && typeof expected != 'object') { } else if (!IS_OBJECT(actual) && !IS_OBJECT(expected)) {
return actual == expected; return actual == expected;
// 7.5 For all other Object pairs, including Array objects, equivalence is // 7.5 For all other Object pairs, including Array objects, equivalence is
@ -184,16 +184,12 @@ function _deepEqual(actual, expected) {
} }
} }
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isArguments(object) { function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]'; return Object.prototype.toString.call(object) == '[object Arguments]';
} }
function objEquiv(a, b) { function objEquiv(a, b) {
if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) if (IS_NULL_OR_UNDEFINED(a) || IS_NULL_OR_UNDEFINED(b))
return false; return false;
// an identical 'prototype' property. // an identical 'prototype' property.
if (a.prototype !== b.prototype) return false; if (a.prototype !== b.prototype) return false;
@ -281,7 +277,7 @@ function expectedException(actual, expected) {
function _throws(shouldThrow, block, expected, message) { function _throws(shouldThrow, block, expected, message) {
var actual; var actual;
if (typeof expected === 'string') { if (IS_STRING(expected)) {
message = expected; message = expected;
expected = null; expected = null;
} }

58
lib/buffer.js

@ -48,34 +48,24 @@ function createPool() {
function Buffer(subject, encoding) { function Buffer(subject, encoding) {
if (!(this instanceof Buffer)) if (!IS_BUFFER(this))
return new Buffer(subject, encoding); return new Buffer(subject, encoding);
var type = typeof subject; if (IS_NUMBER(subject))
this.length = subject > 0 ? Math.floor(subject) : 0;
switch (type) { else if (IS_STRING(subject))
case 'number': this.length = Buffer.byteLength(subject, encoding = encoding || 'utf8');
this.length = subject > 0 ? Math.floor(subject) : 0; else if (IS_OBJECT(subject))
break; this.length = +subject.length > 0 ? Math.floor(+subject.length) : 0;
else if (IS_UNDEFINED(subject)) {
case 'string':
this.length = Buffer.byteLength(subject, encoding = encoding || 'utf8');
break;
case 'object':
this.length = +subject.length > 0 ? Math.floor(+subject.length) : 0;
break;
// undef first arg returns unallocated buffer, also assumes length passed. // undef first arg returns unallocated buffer, also assumes length passed.
// this is a stop-gap for now while look for better architecture. // this is a stop-gap for now while look for better architecture.
// for internal use only. // for internal use only.
case 'undefined': this.length = encoding;
this.length = encoding; return;
return;
default:
throw new TypeError('must start with number, buffer, array or string');
} }
else
throw new TypeError('must start with number, buffer, array or string');
if (this.length > kMaxLength) if (this.length > kMaxLength)
throw new RangeError('length > kMaxLength'); throw new RangeError('length > kMaxLength');
@ -92,14 +82,14 @@ function Buffer(subject, encoding) {
alloc(this, this.length); alloc(this, this.length);
} }
if (type !== 'number') { if (!IS_NUMBER(subject)) {
if (type === 'string') { if (IS_STRING(subject)) {
// FIXME: the number of bytes hasn't changed, so why change the length? // FIXME: the number of bytes hasn't changed, so why change the length?
this.length = this.write(subject, 0, encoding); this.length = this.write(subject, 0, encoding);
} else { } else {
if (subject instanceof Buffer) if (IS_BUFFER(subject))
this.copy(subject, 0, 0, this.length); this.copy(subject, 0, 0, this.length);
else if (typeof subject.length === 'number' || Array.isArray(subject)) else if (IS_NUMBER(subject.length) || IS_ARRAY(subject))
for (var i = 0; i < this.length; i++) for (var i = 0; i < this.length; i++)
this[i] = subject[i]; this[i] = subject[i];
} }
@ -118,7 +108,7 @@ function SlowBuffer(length) {
// Static methods // Static methods
Buffer.isBuffer = function isBuffer(b) { Buffer.isBuffer = function isBuffer(b) {
return b instanceof Buffer; return IS_BUFFER(b);
}; };
@ -144,10 +134,10 @@ Buffer.isEncoding = function(encoding) {
Buffer.concat = function(list, length) { Buffer.concat = function(list, length) {
if (!Array.isArray(list)) if (!IS_ARRAY(list))
throw new TypeError('Usage: Buffer.concat(list[, length])'); throw new TypeError('Usage: Buffer.concat(list[, length])');
if (length === undefined) { if (IS_UNDEFINED(length)) {
length = 0; length = 0;
for (var i = 0; i < list.length; i++) for (var i = 0; i < list.length; i++)
length += list[i].length; length += list[i].length;
@ -184,7 +174,7 @@ Buffer.prototype.toString = function(encoding, start, end) {
encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8'; encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
start = ~~start; start = ~~start;
end = (end === undefined) ? this.length : ~~end; end = IS_UNDEFINED(end) ? this.length : ~~end;
if (start < 0) start = 0; if (start < 0) start = 0;
if (end > this.length) end = this.length; if (end > this.length) end = this.length;
@ -253,7 +243,7 @@ var writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
' Use write(string, offset, length, encoding) instead.'; ' Use write(string, offset, length, encoding) instead.';
Buffer.prototype.write = function(string, offset, length, encoding) { Buffer.prototype.write = function(string, offset, length, encoding) {
// allow write(string, encoding) // allow write(string, encoding)
if (typeof offset === 'string' && length === undefined) { if (IS_STRING(offset) && IS_UNDEFINED(length)) {
encoding = offset; encoding = offset;
offset = 0; offset = 0;
@ -286,7 +276,7 @@ Buffer.prototype.write = function(string, offset, length, encoding) {
} }
var remaining = this.length - offset; var remaining = this.length - offset;
if (length === undefined || length > remaining) if (IS_UNDEFINED(length) || length > remaining)
length = remaining; length = remaining;
encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8'; encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
@ -346,7 +336,7 @@ Buffer.prototype.toJSON = function() {
Buffer.prototype.slice = function(start, end) { Buffer.prototype.slice = function(start, end) {
var len = this.length; var len = this.length;
start = ~~start; start = ~~start;
end = (end === undefined) ? len : ~~end; end = IS_UNDEFINED(end) ? len : ~~end;
if (start < 0) { if (start < 0) {
start += len; start += len;
@ -371,7 +361,7 @@ Buffer.prototype.slice = function(start, end) {
sliceOnto(this, buf, start, end); sliceOnto(this, buf, start, end);
buf.length = end - start; buf.length = end - start;
if (buf.length > 0) if (buf.length > 0)
buf.parent = this.parent === undefined ? this : this.parent; buf.parent = IS_UNDEFINED(this.parent) ? this : this.parent;
return buf; return buf;
}; };

46
lib/child_process.js

@ -39,7 +39,7 @@ function handleWrapGetter(name, callback) {
Object.defineProperty(handleWraps, name, { Object.defineProperty(handleWraps, name, {
get: function() { get: function() {
if (cons !== undefined) return cons; if (!IS_UNDEFINED(cons)) return cons;
return cons = callback(); return cons = callback();
} }
}); });
@ -312,9 +312,9 @@ function getSocketList(type, slave, key) {
var INTERNAL_PREFIX = 'NODE_'; var INTERNAL_PREFIX = 'NODE_';
function handleMessage(target, message, handle) { function handleMessage(target, message, handle) {
var eventName = 'message'; var eventName = 'message';
if (message !== null && if (!IS_NULL(message) &&
typeof message === 'object' && IS_OBJECT(message) &&
typeof message.cmd === 'string' && IS_STRING(message.cmd) &&
message.cmd.length > INTERNAL_PREFIX.length && message.cmd.length > INTERNAL_PREFIX.length &&
message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX) { message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX) {
eventName = 'internalMessage'; eventName = 'internalMessage';
@ -370,7 +370,7 @@ function setupChannel(target, channel) {
target.on('internalMessage', function(message, handle) { target.on('internalMessage', function(message, handle) {
// Once acknowledged - continue sending handles. // Once acknowledged - continue sending handles.
if (message.cmd === 'NODE_HANDLE_ACK') { if (message.cmd === 'NODE_HANDLE_ACK') {
assert(Array.isArray(target._handleQueue)); assert(IS_ARRAY(target._handleQueue));
var queue = target._handleQueue; var queue = target._handleQueue;
target._handleQueue = null; target._handleQueue = null;
queue.forEach(function(args) { queue.forEach(function(args) {
@ -399,7 +399,7 @@ function setupChannel(target, channel) {
}); });
target.send = function(message, handle) { target.send = function(message, handle) {
if (typeof message === 'undefined') { if (IS_UNDEFINED(message)) {
throw new TypeError('message cannot be undefined'); throw new TypeError('message cannot be undefined');
} }
@ -512,7 +512,7 @@ exports.fork = function(modulePath /*, args, options*/) {
// Get options and args arguments. // Get options and args arguments.
var options, args, execArgv; var options, args, execArgv;
if (Array.isArray(arguments[1])) { if (IS_ARRAY(arguments[1])) {
args = arguments[1]; args = arguments[1];
options = util._extend({}, arguments[2]); options = util._extend({}, arguments[2]);
} else { } else {
@ -557,7 +557,7 @@ exports._forkChild = function(fd) {
exports.exec = function(command /*, options, callback */) { exports.exec = function(command /*, options, callback */) {
var file, args, options, callback; var file, args, options, callback;
if (typeof arguments[1] === 'function') { if (IS_FUNCTION(arguments[1])) {
options = undefined; options = undefined;
callback = arguments[1]; callback = arguments[1];
} else { } else {
@ -593,11 +593,11 @@ exports.execFile = function(file /* args, options, callback */) {
// Parse the parameters. // Parse the parameters.
if (typeof arguments[arguments.length - 1] === 'function') { if (IS_FUNCTION(arguments[arguments.length - 1])) {
callback = arguments[arguments.length - 1]; callback = arguments[arguments.length - 1];
} }
if (Array.isArray(arguments[1])) { if (IS_ARRAY(arguments[1])) {
args = arguments[1]; args = arguments[1];
options = util._extend(options, arguments[2]); options = util._extend(options, arguments[2]);
} else { } else {
@ -835,14 +835,14 @@ ChildProcess.prototype.spawn = function(options) {
stdio = options.stdio || 'pipe'; stdio = options.stdio || 'pipe';
// Replace shortcut with an array // Replace shortcut with an array
if (typeof stdio === 'string') { if (IS_STRING(stdio)) {
switch (stdio) { switch (stdio) {
case 'ignore': stdio = ['ignore', 'ignore', 'ignore']; break; case 'ignore': stdio = ['ignore', 'ignore', 'ignore']; break;
case 'pipe': stdio = ['pipe', 'pipe', 'pipe']; break; case 'pipe': stdio = ['pipe', 'pipe', 'pipe']; break;
case 'inherit': stdio = [0, 1, 2]; break; case 'inherit': stdio = [0, 1, 2]; break;
default: throw new TypeError('Incorrect value of stdio option: ' + stdio); default: throw new TypeError('Incorrect value of stdio option: ' + stdio);
} }
} else if (!Array.isArray(stdio)) { } else if (!IS_ARRAY(stdio)) {
throw new TypeError('Incorrect value of stdio option: ' + stdio); throw new TypeError('Incorrect value of stdio option: ' + stdio);
} }
@ -864,16 +864,16 @@ ChildProcess.prototype.spawn = function(options) {
} }
// Defaults // Defaults
if (stdio === undefined || stdio === null) { if (IS_NULL_OR_UNDEFINED(stdio)) {
stdio = i < 3 ? 'pipe' : 'ignore'; stdio = i < 3 ? 'pipe' : 'ignore';
} }
if (stdio === 'ignore') { if (stdio === 'ignore') {
acc.push({type: 'ignore'}); acc.push({type: 'ignore'});
} else if (stdio === 'pipe' || typeof stdio === 'number' && stdio < 0) { } else if (stdio === 'pipe' || IS_NUMBER(stdio) && stdio < 0) {
acc.push({type: 'pipe', handle: createPipe()}); acc.push({type: 'pipe', handle: createPipe()});
} else if (stdio === 'ipc') { } else if (stdio === 'ipc') {
if (ipc !== undefined) { if (!IS_UNDEFINED(ipc)) {
// Cleanup previously created pipes // Cleanup previously created pipes
cleanup(); cleanup();
throw Error('Child process can have only one IPC pipe'); throw Error('Child process can have only one IPC pipe');
@ -883,7 +883,7 @@ ChildProcess.prototype.spawn = function(options) {
ipcFd = i; ipcFd = i;
acc.push({ type: 'pipe', handle: ipc, ipc: true }); acc.push({ type: 'pipe', handle: ipc, ipc: true });
} else if (typeof stdio === 'number' || typeof stdio.fd === 'number') { } else if (IS_NUMBER(stdio) || IS_NUMBER(stdio.fd)) {
acc.push({ type: 'fd', fd: stdio.fd || stdio }); acc.push({ type: 'fd', fd: stdio.fd || stdio });
} else if (getHandleWrapType(stdio) || getHandleWrapType(stdio.handle) || } else if (getHandleWrapType(stdio) || getHandleWrapType(stdio.handle) ||
getHandleWrapType(stdio._handle)) { getHandleWrapType(stdio._handle)) {
@ -907,7 +907,7 @@ ChildProcess.prototype.spawn = function(options) {
options.stdio = stdio; options.stdio = stdio;
if (ipc !== undefined) { if (!IS_UNDEFINED(ipc)) {
// Let child process know about opened IPC channel // Let child process know about opened IPC channel
options.envPairs = options.envPairs || []; options.envPairs = options.envPairs || [];
options.envPairs.push('NODE_CHANNEL_FD=' + ipcFd); options.envPairs.push('NODE_CHANNEL_FD=' + ipcFd);
@ -952,19 +952,19 @@ ChildProcess.prototype.spawn = function(options) {
} }
}); });
this.stdin = stdio.length >= 1 && stdio[0].socket !== undefined ? this.stdin = stdio.length >= 1 && !IS_UNDEFINED(stdio[0].socket) ?
stdio[0].socket : null; stdio[0].socket : null;
this.stdout = stdio.length >= 2 && stdio[1].socket !== undefined ? this.stdout = stdio.length >= 2 && !IS_UNDEFINED(stdio[1].socket) ?
stdio[1].socket : null; stdio[1].socket : null;
this.stderr = stdio.length >= 3 && stdio[2].socket !== undefined ? this.stderr = stdio.length >= 3 && !IS_UNDEFINED(stdio[2].socket) ?
stdio[2].socket : null; stdio[2].socket : null;
this.stdio = stdio.map(function(stdio) { this.stdio = stdio.map(function(stdio) {
return stdio.socket === undefined ? null : stdio.socket; return IS_UNDEFINED(stdio.socket) ? null : stdio.socket;
}); });
// Add .send() method and start listening for IPC data // Add .send() method and start listening for IPC data
if (ipc !== undefined) setupChannel(this, ipc); if (!IS_UNDEFINED(ipc)) setupChannel(this, ipc);
return err; return err;
}; };
@ -985,7 +985,7 @@ ChildProcess.prototype.kill = function(sig) {
signal = constants[sig]; signal = constants[sig];
} }
if (signal === undefined) { if (IS_UNDEFINED(signal)) {
throw new Error('Unknown signal: ' + sig); throw new Error('Unknown signal: ' + sig);
} }

20
lib/cluster.js

@ -68,7 +68,7 @@ function SharedHandle(key, address, port, addressType, backlog, fd) {
else else
rval = net._createServerHandle(address, port, addressType, fd); rval = net._createServerHandle(address, port, addressType, fd);
if (typeof rval === 'number') if (IS_NUMBER(rval))
this.errno = rval; this.errno = rval;
else else
this.handle = rval; this.handle = rval;
@ -135,7 +135,7 @@ RoundRobinHandle.prototype.add = function(worker, send) {
self.handoff(worker); // In case there are connections pending. self.handoff(worker); // In case there are connections pending.
} }
if (this.server === null) return done(); if (IS_NULL(this.server)) return done();
// Still busy binding. // Still busy binding.
this.server.once('listening', done); this.server.once('listening', done);
this.server.once('error', function(err) { this.server.once('error', function(err) {
@ -166,7 +166,7 @@ RoundRobinHandle.prototype.handoff = function(worker) {
return; // Worker is closing (or has closed) the server. return; // Worker is closing (or has closed) the server.
} }
var handle = this.handles.shift(); var handle = this.handles.shift();
if (typeof handle === 'undefined') { if (IS_UNDEFINED(handle)) {
this.free.push(worker); // Add to ready queue again. this.free.push(worker); // Add to ready queue again.
return; return;
} }
@ -225,7 +225,7 @@ function masterInit() {
'rr': SCHED_RR 'rr': SCHED_RR
}[process.env.NODE_CLUSTER_SCHED_POLICY]; }[process.env.NODE_CLUSTER_SCHED_POLICY];
if (typeof schedulingPolicy === 'undefined') { if (IS_UNDEFINED(schedulingPolicy)) {
// FIXME Round-robin doesn't perform well on Windows right now due to the // FIXME Round-robin doesn't perform well on Windows right now due to the
// way IOCP is wired up. Bert is going to fix that, eventually. // way IOCP is wired up. Bert is going to fix that, eventually.
schedulingPolicy = (process.platform === 'win32') ? SCHED_NONE : SCHED_RR; schedulingPolicy = (process.platform === 'win32') ? SCHED_NONE : SCHED_RR;
@ -367,7 +367,7 @@ function masterInit() {
message.fd]; message.fd];
var key = args.join(':'); var key = args.join(':');
var handle = handles[key]; var handle = handles[key];
if (typeof handle === 'undefined') { if (IS_UNDEFINED(handle)) {
var constructor = RoundRobinHandle; var constructor = RoundRobinHandle;
// UDP is exempt from round-robin connection balancing for what should // UDP is exempt from round-robin connection balancing for what should
// be obvious reasons: it's connectionless. There is nothing to send to // be obvious reasons: it's connectionless. There is nothing to send to
@ -474,7 +474,7 @@ function workerInit() {
delete handles[key]; delete handles[key];
return close.apply(this, arguments); return close.apply(this, arguments);
}; };
assert(typeof handles[key] === 'undefined'); assert(IS_UNDEFINED(handles[key]));
handles[key] = handle; handles[key] = handle;
cb(handle); cb(handle);
} }
@ -511,7 +511,7 @@ function workerInit() {
// the ack by the master process in which we can still receive handles. // the ack by the master process in which we can still receive handles.
// onconnection() below handles that by sending those handles back to // onconnection() below handles that by sending those handles back to
// the master. // the master.
if (typeof key === 'undefined') return; if (IS_UNDEFINED(key)) return;
send({ act: 'close', key: key }); send({ act: 'close', key: key });
delete handles[key]; delete handles[key];
key = undefined; key = undefined;
@ -529,7 +529,7 @@ function workerInit() {
if (message.sockname) { if (message.sockname) {
handle.getsockname = getsockname; // TCP handles only. handle.getsockname = getsockname; // TCP handles only.
} }
assert(typeof handles[key] === 'undefined'); assert(IS_UNDEFINED(handles[key]));
handles[key] = handle; handles[key] = handle;
cb(handle); cb(handle);
} }
@ -539,7 +539,7 @@ function workerInit() {
function onconnection(message, handle) { function onconnection(message, handle) {
var key = message.key; var key = message.key;
var server = handles[key]; var server = handles[key];
var accepted = (typeof server !== 'undefined'); var accepted = !IS_UNDEFINED(server);
send({ ack: message.seq, accepted: accepted }); send({ ack: message.seq, accepted: accepted });
if (accepted) server.onconnection(0, handle); if (accepted) server.onconnection(0, handle);
} }
@ -585,7 +585,7 @@ function internal(worker, cb) {
return function(message, handle) { return function(message, handle) {
if (message.cmd !== 'NODE_CLUSTER') return; if (message.cmd !== 'NODE_CLUSTER') return;
var fn = cb; var fn = cb;
if (typeof message.ack !== 'undefined') { if (!IS_UNDEFINED(message.ack)) {
fn = callbacks[message.ack]; fn = callbacks[message.ack];
delete callbacks[message.ack]; delete callbacks[message.ack];
} }

2
lib/console.js

@ -25,7 +25,7 @@ function Console(stdout, stderr) {
if (!(this instanceof Console)) { if (!(this instanceof Console)) {
return new Console(stdout, stderr); return new Console(stdout, stderr);
} }
if (!stdout || typeof stdout.write !== 'function') { if (!stdout || !IS_FUNCTION(stdout.write)) {
throw new TypeError('Console expects a writable stream instance'); throw new TypeError('Console expects a writable stream instance');
} }
if (!stderr) { if (!stderr) {

10
lib/crypto.js

@ -43,7 +43,7 @@ var util = require('util');
// to break them unnecessarily. // to break them unnecessarily.
function toBuf(str, encoding) { function toBuf(str, encoding) {
encoding = encoding || 'binary'; encoding = encoding || 'binary';
if (typeof str === 'string') { if (IS_STRING(str)) {
if (encoding === 'buffer') if (encoding === 'buffer')
encoding = 'binary'; encoding = 'binary';
str = new Buffer(str, encoding); str = new Buffer(str, encoding);
@ -100,7 +100,7 @@ exports.createCredentials = function(options, context) {
if (options.ciphers) c.context.setCiphers(options.ciphers); if (options.ciphers) c.context.setCiphers(options.ciphers);
if (options.ca) { if (options.ca) {
if (Array.isArray(options.ca)) { if (IS_ARRAY(options.ca)) {
for (var i = 0, len = options.ca.length; i < len; i++) { for (var i = 0, len = options.ca.length; i < len; i++) {
c.context.addCACert(options.ca[i]); c.context.addCACert(options.ca[i]);
} }
@ -112,7 +112,7 @@ exports.createCredentials = function(options, context) {
} }
if (options.crl) { if (options.crl) {
if (Array.isArray(options.crl)) { if (IS_ARRAY(options.crl)) {
for (var i = 0, len = options.crl.length; i < len; i++) { for (var i = 0, len = options.crl.length; i < len; i++) {
c.context.addCRL(options.crl[i]); c.context.addCRL(options.crl[i]);
} }
@ -198,7 +198,7 @@ Hash.prototype._flush = function(callback) {
Hash.prototype.update = function(data, encoding) { Hash.prototype.update = function(data, encoding) {
encoding = encoding || exports.DEFAULT_ENCODING; encoding = encoding || exports.DEFAULT_ENCODING;
if (encoding === 'buffer' && typeof data === 'string') if (encoding === 'buffer' && IS_STRING(data))
encoding = 'binary'; encoding = 'binary';
this._binding.update(data, encoding); this._binding.update(data, encoding);
return this; return this;
@ -539,7 +539,7 @@ DiffieHellman.prototype.setPrivateKey = function(key, encoding) {
exports.pbkdf2 = function(password, salt, iterations, keylen, callback) { exports.pbkdf2 = function(password, salt, iterations, keylen, callback) {
if (typeof callback !== 'function') if (!IS_FUNCTION(callback))
throw new Error('No callback provided to pbkdf2'); throw new Error('No callback provided to pbkdf2');
return pbkdf2(password, salt, iterations, keylen, callback); return pbkdf2(password, salt, iterations, keylen, callback);

18
lib/dgram.js

@ -91,7 +91,7 @@ function newHandle(type) {
exports._createSocketHandle = function(address, port, addressType, fd) { exports._createSocketHandle = function(address, port, addressType, fd) {
// Opening an existing fd is not supported for UDP handles. // Opening an existing fd is not supported for UDP handles.
assert(typeof fd !== 'number' || fd < 0); assert(!IS_NUMBER(fd) || fd < 0);
var handle = newHandle(addressType); var handle = newHandle(addressType);
@ -119,7 +119,7 @@ function Socket(type, listener) {
this.type = type; this.type = type;
this.fd = null; // compatibility hack this.fd = null; // compatibility hack
if (typeof listener === 'function') if (IS_FUNCTION(listener))
this.on('message', listener); this.on('message', listener);
} }
util.inherits(Socket, events.EventEmitter); util.inherits(Socket, events.EventEmitter);
@ -165,7 +165,7 @@ Socket.prototype.bind = function(/*port, address, callback*/) {
this._bindState = BIND_STATE_BINDING; this._bindState = BIND_STATE_BINDING;
if (typeof arguments[arguments.length - 1] === 'function') if (IS_FUNCTION(arguments[arguments.length - 1]))
self.once('listening', arguments[arguments.length - 1]); self.once('listening', arguments[arguments.length - 1]);
var UDP = process.binding('udp_wrap').UDP; var UDP = process.binding('udp_wrap').UDP;
@ -177,7 +177,7 @@ Socket.prototype.bind = function(/*port, address, callback*/) {
var port = arguments[0]; var port = arguments[0];
var address = arguments[1]; var address = arguments[1];
if (typeof address === 'function') address = ''; // a.k.a. "any address" if (IS_FUNCTION(address)) address = ''; // a.k.a. "any address"
// resolve address first // resolve address first
self._handle.lookup(address, function(err, ip) { self._handle.lookup(address, function(err, ip) {
@ -225,10 +225,10 @@ Socket.prototype.sendto = function(buffer,
port, port,
address, address,
callback) { callback) {
if (typeof offset !== 'number' || typeof length !== 'number') if (!IS_NUMBER(offset) || !IS_NUMBER(length))
throw new Error('send takes offset and length as args 2 and 3'); throw new Error('send takes offset and length as args 2 and 3');
if (typeof address !== 'string') if (!IS_STRING(address))
throw new Error(this.type + ' sockets must send to port, address'); throw new Error(this.type + ' sockets must send to port, address');
this.send(buffer, offset, length, port, address, callback); this.send(buffer, offset, length, port, address, callback);
@ -243,7 +243,7 @@ Socket.prototype.send = function(buffer,
callback) { callback) {
var self = this; var self = this;
if (!Buffer.isBuffer(buffer)) if (!IS_BUFFER(buffer))
throw new TypeError('First argument must be a buffer object.'); throw new TypeError('First argument must be a buffer object.');
if (offset >= buffer.length) if (offset >= buffer.length)
@ -335,7 +335,7 @@ Socket.prototype.setBroadcast = function(arg) {
Socket.prototype.setTTL = function(arg) { Socket.prototype.setTTL = function(arg) {
if (typeof arg !== 'number') { if (!IS_NUMBER(arg)) {
throw new TypeError('Argument must be a number'); throw new TypeError('Argument must be a number');
} }
@ -349,7 +349,7 @@ Socket.prototype.setTTL = function(arg) {
Socket.prototype.setMulticastTTL = function(arg) { Socket.prototype.setMulticastTTL = function(arg) {
if (typeof arg !== 'number') { if (!IS_NUMBER(arg)) {
throw new TypeError('Argument must be a number'); throw new TypeError('Argument must be a number');
} }

6
lib/dns.js

@ -61,7 +61,7 @@ function errnoException(err, syscall) {
// callback.immediately = true; // callback.immediately = true;
// } // }
function makeAsync(callback) { function makeAsync(callback) {
if (typeof callback !== 'function') { if (!IS_FUNCTION(callback)) {
return callback; return callback;
} }
return function asyncCallback() { return function asyncCallback() {
@ -178,7 +178,7 @@ exports.reverse = resolveMap.PTR = resolver('getHostByAddr');
exports.resolve = function(domain, type_, callback_) { exports.resolve = function(domain, type_, callback_) {
var resolver, callback; var resolver, callback;
if (typeof type_ == 'string') { if (IS_STRING(type_)) {
resolver = resolveMap[type_]; resolver = resolveMap[type_];
callback = callback_; callback = callback_;
} else { } else {
@ -186,7 +186,7 @@ exports.resolve = function(domain, type_, callback_) {
callback = type_; callback = type_;
} }
if (typeof resolver === 'function') { if (IS_FUNCTION(resolver)) {
return resolver(domain, callback); return resolver(domain, callback);
} else { } else {
throw new Error('Unknown type "' + type_ + '"'); throw new Error('Unknown type "' + type_ + '"');

2
lib/domain.js

@ -219,7 +219,7 @@ Domain.prototype.dispose = function() {
// so it's quite possible that calling some of these methods // so it's quite possible that calling some of these methods
// might cause additional exceptions to be thrown. // might cause additional exceptions to be thrown.
endMethods.forEach(function(method) { endMethods.forEach(function(method) {
if (typeof m[method] === 'function') { if (IS_FUNCTION(m[method])) {
try { try {
m[method](); m[method]();
} catch (er) {} } catch (er) {}

37
lib/events.js

@ -49,7 +49,7 @@ EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows // Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited. // that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) { EventEmitter.prototype.setMaxListeners = function(n) {
if (typeof n !== 'number' || n < 0) if (!IS_NUMBER(n) || n < 0)
throw TypeError('n must be a positive number'); throw TypeError('n must be a positive number');
this._maxListeners = n; this._maxListeners = n;
return this; return this;
@ -64,8 +64,7 @@ EventEmitter.prototype.emit = function(type) {
// If there is no 'error' event listener then throw. // If there is no 'error' event listener then throw.
if (type === 'error') { if (type === 'error') {
if (!this._events.error || if (!this._events.error ||
(typeof this._events.error === 'object' && (IS_OBJECT(this._events.error) && !this._events.error.length)) {
!this._events.error.length)) {
er = arguments[1]; er = arguments[1];
if (this.domain) { if (this.domain) {
if (!er) er = new TypeError('Uncaught, unspecified "error" event.'); if (!er) er = new TypeError('Uncaught, unspecified "error" event.');
@ -84,13 +83,13 @@ EventEmitter.prototype.emit = function(type) {
handler = this._events[type]; handler = this._events[type];
if (typeof handler === 'undefined') if (IS_UNDEFINED(handler))
return false; return false;
if (this.domain && this !== process) if (this.domain && this !== process)
this.domain.enter(); this.domain.enter();
if (typeof handler === 'function') { if (IS_FUNCTION(handler)) {
switch (arguments.length) { switch (arguments.length) {
// fast cases // fast cases
case 1: case 1:
@ -110,7 +109,7 @@ EventEmitter.prototype.emit = function(type) {
args[i - 1] = arguments[i]; args[i - 1] = arguments[i];
handler.apply(this, args); handler.apply(this, args);
} }
} else if (typeof handler === 'object') { } else if (IS_OBJECT(handler)) {
len = arguments.length; len = arguments.length;
args = new Array(len - 1); args = new Array(len - 1);
for (i = 1; i < len; i++) for (i = 1; i < len; i++)
@ -131,7 +130,7 @@ EventEmitter.prototype.emit = function(type) {
EventEmitter.prototype.addListener = function(type, listener) { EventEmitter.prototype.addListener = function(type, listener) {
var m; var m;
if (typeof listener !== 'function') if (!IS_FUNCTION(listener))
throw TypeError('listener must be a function'); throw TypeError('listener must be a function');
if (!this._events) if (!this._events)
@ -140,13 +139,13 @@ EventEmitter.prototype.addListener = function(type, listener) {
// To avoid recursion in the case that type === "newListener"! Before // To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener". // adding it to the listeners, first emit "newListener".
if (this._events.newListener) if (this._events.newListener)
this.emit('newListener', type, typeof listener.listener === 'function' ? this.emit('newListener', type,
listener.listener : listener); IS_FUNCTION(listener.listener) ? listener.listener : listener);
if (!this._events[type]) if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object. // Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener; this._events[type] = listener;
else if (typeof this._events[type] === 'object') else if (IS_OBJECT(this._events[type]))
// If we've already got an array, just append. // If we've already got an array, just append.
this._events[type].push(listener); this._events[type].push(listener);
else else
@ -154,9 +153,9 @@ EventEmitter.prototype.addListener = function(type, listener) {
this._events[type] = [this._events[type], listener]; this._events[type] = [this._events[type], listener];
// Check for listener leak // Check for listener leak
if (typeof this._events[type] === 'object' && !this._events[type].warned) { if (IS_OBJECT(this._events[type]) && !this._events[type].warned) {
var m; var m;
if (this._maxListeners !== undefined) { if (!IS_UNDEFINED(this._maxListeners)) {
m = this._maxListeners; m = this._maxListeners;
} else { } else {
m = EventEmitter.defaultMaxListeners; m = EventEmitter.defaultMaxListeners;
@ -178,7 +177,7 @@ EventEmitter.prototype.addListener = function(type, listener) {
EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) { EventEmitter.prototype.once = function(type, listener) {
if (typeof listener !== 'function') if (!IS_FUNCTION(listener))
throw TypeError('listener must be a function'); throw TypeError('listener must be a function');
function g() { function g() {
@ -196,7 +195,7 @@ EventEmitter.prototype.once = function(type, listener) {
EventEmitter.prototype.removeListener = function(type, listener) { EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i; var list, position, length, i;
if (typeof listener !== 'function') if (!IS_FUNCTION(listener))
throw TypeError('listener must be a function'); throw TypeError('listener must be a function');
if (!this._events || !this._events[type]) if (!this._events || !this._events[type])
@ -207,12 +206,12 @@ EventEmitter.prototype.removeListener = function(type, listener) {
position = -1; position = -1;
if (list === listener || if (list === listener ||
(typeof list.listener === 'function' && list.listener === listener)) { (IS_FUNCTION(list.listener) && list.listener === listener)) {
this._events[type] = undefined; this._events[type] = undefined;
if (this._events.removeListener) if (this._events.removeListener)
this.emit('removeListener', type, listener); this.emit('removeListener', type, listener);
} else if (typeof list === 'object') { } else if (IS_OBJECT(list)) {
for (i = length; i-- > 0;) { for (i = length; i-- > 0;) {
if (list[i] === listener || if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) { (list[i].listener && list[i].listener === listener)) {
@ -266,7 +265,7 @@ EventEmitter.prototype.removeAllListeners = function(type) {
listeners = this._events[type]; listeners = this._events[type];
if (typeof listeners === 'function') { if (IS_FUNCTION(listeners)) {
this.removeListener(type, listeners); this.removeListener(type, listeners);
} else { } else {
// LIFO order // LIFO order
@ -282,7 +281,7 @@ EventEmitter.prototype.listeners = function(type) {
var ret; var ret;
if (!this._events || !this._events[type]) if (!this._events || !this._events[type])
ret = []; ret = [];
else if (typeof this._events[type] === 'function') else if (IS_FUNCTION(this._events[type]))
ret = [this._events[type]]; ret = [this._events[type]];
else else
ret = this._events[type].slice(); ret = this._events[type].slice();
@ -293,7 +292,7 @@ EventEmitter.listenerCount = function(emitter, type) {
var ret; var ret;
if (!emitter._events || !emitter._events[type]) if (!emitter._events || !emitter._events[type])
ret = 0; ret = 0;
else if (typeof emitter._events[type] === 'function') else if (IS_FUNCTION(emitter._events[type]))
ret = 1; ret = 1;
else else
ret = emitter._events[type].length; ret = emitter._events[type].length;

145
lib/fs.js

@ -81,14 +81,14 @@ function rethrow() {
} }
function maybeCallback(cb) { function maybeCallback(cb) {
return typeof cb === 'function' ? cb : rethrow(); return IS_FUNCTION(cb) ? cb : rethrow();
} }
// Ensure that callbacks run in the global context. Only use this function // Ensure that callbacks run in the global context. Only use this function
// for callbacks that are passed to the binding layer, callbacks that are // for callbacks that are passed to the binding layer, callbacks that are
// invoked from JS already run in the proper scope. // invoked from JS already run in the proper scope.
function makeCallback(cb) { function makeCallback(cb) {
if (typeof cb !== 'function') { if (!IS_FUNCTION(cb)) {
return rethrow(); return rethrow();
} }
@ -171,13 +171,13 @@ fs.existsSync = function(path) {
fs.readFile = function(path, options, callback_) { fs.readFile = function(path, options, callback_) {
var callback = maybeCallback(arguments[arguments.length - 1]); var callback = maybeCallback(arguments[arguments.length - 1]);
if (typeof options === 'function' || !options) { if (IS_FUNCTION(options) || !options) {
options = { encoding: null, flag: 'r' }; options = { encoding: null, flag: 'r' };
} else if (typeof options === 'string') { } else if (IS_STRING(options)) {
options = { encoding: options, flag: 'r' }; options = { encoding: options, flag: 'r' };
} else if (!options) { } else if (!options) {
options = { encoding: null, flag: 'r' }; options = { encoding: null, flag: 'r' };
} else if (typeof options !== 'object') { } else if (!IS_OBJECT(options)) {
throw new TypeError('Bad arguments'); throw new TypeError('Bad arguments');
} }
@ -260,9 +260,9 @@ fs.readFile = function(path, options, callback_) {
fs.readFileSync = function(path, options) { fs.readFileSync = function(path, options) {
if (!options) { if (!options) {
options = { encoding: null, flag: 'r' }; options = { encoding: null, flag: 'r' };
} else if (typeof options === 'string') { } else if (IS_STRING(options)) {
options = { encoding: options, flag: 'r' }; options = { encoding: options, flag: 'r' };
} else if (typeof options !== 'object') { } else if (!IS_OBJECT(options)) {
throw new TypeError('Bad arguments'); throw new TypeError('Bad arguments');
} }
@ -332,7 +332,7 @@ fs.readFileSync = function(path, options) {
// Used by binding.open and friends // Used by binding.open and friends
function stringToFlags(flag) { function stringToFlags(flag) {
// Only mess with strings // Only mess with strings
if (typeof flag !== 'string') { if (!IS_STRING(flag)) {
return flag; return flag;
} }
@ -381,16 +381,13 @@ fs.closeSync = function(fd) {
}; };
function modeNum(m, def) { function modeNum(m, def) {
switch (typeof m) { if (IS_NUMBER(m))
case 'number': return m; return m;
case 'string': return parseInt(m, 8); if (IS_STRING(m))
default: return parseInt(m, 8);
if (def) { if (def)
return modeNum(def); return modeNum(def);
} else { return undefined;
return undefined;
}
}
} }
fs.open = function(path, flags, mode, callback) { fs.open = function(path, flags, mode, callback) {
@ -411,7 +408,7 @@ fs.openSync = function(path, flags, mode) {
}; };
fs.read = function(fd, buffer, offset, length, position, callback) { fs.read = function(fd, buffer, offset, length, position, callback) {
if (!Buffer.isBuffer(buffer)) { if (!IS_BUFFER(buffer)) {
// legacy string interface (fd, length, position, encoding, callback) // legacy string interface (fd, length, position, encoding, callback)
var cb = arguments[4], var cb = arguments[4],
encoding = arguments[3]; encoding = arguments[3];
@ -442,7 +439,7 @@ fs.read = function(fd, buffer, offset, length, position, callback) {
fs.readSync = function(fd, buffer, offset, length, position) { fs.readSync = function(fd, buffer, offset, length, position) {
var legacy = false; var legacy = false;
if (!Buffer.isBuffer(buffer)) { if (!IS_BUFFER(buffer)) {
// legacy string interface (fd, length, position, encoding, callback) // legacy string interface (fd, length, position, encoding, callback)
legacy = true; legacy = true;
var encoding = arguments[3]; var encoding = arguments[3];
@ -466,7 +463,7 @@ fs.readSync = function(fd, buffer, offset, length, position) {
}; };
fs.write = function(fd, buffer, offset, length, position, callback) { fs.write = function(fd, buffer, offset, length, position, callback) {
if (!Buffer.isBuffer(buffer)) { if (!IS_BUFFER(buffer)) {
// legacy string interface (fd, data, position, encoding, callback) // legacy string interface (fd, data, position, encoding, callback)
callback = arguments[4]; callback = arguments[4];
position = arguments[2]; position = arguments[2];
@ -478,7 +475,7 @@ fs.write = function(fd, buffer, offset, length, position, callback) {
} }
if (!length) { if (!length) {
if (typeof callback == 'function') { if (IS_FUNCTION(callback)) {
process.nextTick(function() { process.nextTick(function() {
callback(undefined, 0); callback(undefined, 0);
}); });
@ -497,7 +494,7 @@ fs.write = function(fd, buffer, offset, length, position, callback) {
}; };
fs.writeSync = function(fd, buffer, offset, length, position) { fs.writeSync = function(fd, buffer, offset, length, position) {
if (!Buffer.isBuffer(buffer)) { if (!IS_BUFFER(buffer)) {
// legacy string interface (fd, data, position, encoding) // legacy string interface (fd, data, position, encoding)
position = arguments[2]; position = arguments[2];
assertEncoding(arguments[3]); assertEncoding(arguments[3]);
@ -528,14 +525,14 @@ fs.renameSync = function(oldPath, newPath) {
}; };
fs.truncate = function(path, len, callback) { fs.truncate = function(path, len, callback) {
if (typeof path === 'number') { if (IS_NUMBER(path)) {
// legacy // legacy
return fs.ftruncate(path, len, callback); return fs.ftruncate(path, len, callback);
} }
if (typeof len === 'function') { if (IS_FUNCTION(len)) {
callback = len; callback = len;
len = 0; len = 0;
} else if (typeof len === 'undefined') { } else if (IS_UNDEFINED(len)) {
len = 0; len = 0;
} }
callback = maybeCallback(callback); callback = maybeCallback(callback);
@ -550,11 +547,11 @@ fs.truncate = function(path, len, callback) {
}; };
fs.truncateSync = function(path, len) { fs.truncateSync = function(path, len) {
if (typeof path === 'number') { if (IS_NUMBER(path)) {
// legacy // legacy
return fs.ftruncateSync(path, len); return fs.ftruncateSync(path, len);
} }
if (typeof len === 'undefined') { if (IS_UNDEFINED(len)) {
len = 0; len = 0;
} }
// allow error to be thrown, but still close fd. // allow error to be thrown, but still close fd.
@ -568,17 +565,17 @@ fs.truncateSync = function(path, len) {
}; };
fs.ftruncate = function(fd, len, callback) { fs.ftruncate = function(fd, len, callback) {
if (typeof len === 'function') { if (IS_FUNCTION(len)) {
callback = len; callback = len;
len = 0; len = 0;
} else if (typeof len === 'undefined') { } else if (IS_UNDEFINED(len)) {
len = 0; len = 0;
} }
binding.ftruncate(fd, len, makeCallback(callback)); binding.ftruncate(fd, len, makeCallback(callback));
}; };
fs.ftruncateSync = function(fd, len) { fs.ftruncateSync = function(fd, len) {
if (typeof len === 'undefined') { if (IS_UNDEFINED(len)) {
len = 0; len = 0;
} }
return binding.ftruncate(fd, len); return binding.ftruncate(fd, len);
@ -612,7 +609,7 @@ fs.fsyncSync = function(fd) {
}; };
fs.mkdir = function(path, mode, callback) { fs.mkdir = function(path, mode, callback) {
if (typeof mode === 'function') callback = mode; if (IS_FUNCTION(mode)) callback = mode;
callback = makeCallback(callback); callback = makeCallback(callback);
if (!nullCheck(path, callback)) return; if (!nullCheck(path, callback)) return;
binding.mkdir(pathModule._makeLong(path), binding.mkdir(pathModule._makeLong(path),
@ -692,7 +689,7 @@ function preprocessSymlinkDestination(path, type) {
} }
fs.symlink = function(destination, path, type_, callback) { fs.symlink = function(destination, path, type_, callback) {
var type = (typeof type_ === 'string' ? type_ : null); var type = (IS_STRING(type_) ? type_ : null);
var callback = makeCallback(arguments[arguments.length - 1]); var callback = makeCallback(arguments[arguments.length - 1]);
if (!nullCheck(destination, callback)) return; if (!nullCheck(destination, callback)) return;
@ -705,7 +702,7 @@ fs.symlink = function(destination, path, type_, callback) {
}; };
fs.symlinkSync = function(destination, path, type) { fs.symlinkSync = function(destination, path, type) {
type = (typeof type === 'string' ? type : null); type = (IS_STRING(type) ? type : null);
nullCheck(destination); nullCheck(destination);
nullCheck(path); nullCheck(path);
@ -843,10 +840,10 @@ fs.chownSync = function(path, uid, gid) {
// converts Date or number to a fractional UNIX timestamp // converts Date or number to a fractional UNIX timestamp
function toUnixTimestamp(time) { function toUnixTimestamp(time) {
if (typeof time == 'number') { if (IS_NUMBER(time)) {
return time; return time;
} }
if (time instanceof Date) { if (IS_DATE(time)) {
// convert to 123.456 UNIX timestamp // convert to 123.456 UNIX timestamp
return time.getTime() / 1000; return time.getTime() / 1000;
} }
@ -909,13 +906,13 @@ function writeAll(fd, buffer, offset, length, position, callback) {
fs.writeFile = function(path, data, options, callback) { fs.writeFile = function(path, data, options, callback) {
var callback = maybeCallback(arguments[arguments.length - 1]); var callback = maybeCallback(arguments[arguments.length - 1]);
if (typeof options === 'function' || !options) { if (IS_FUNCTION(options) || !options) {
options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' }; options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' };
} else if (typeof options === 'string') { } else if (IS_STRING(options)) {
options = { encoding: options, mode: 438, flag: 'w' }; options = { encoding: options, mode: 438, flag: 'w' };
} else if (!options) { } else if (!options) {
options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' }; options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' };
} else if (typeof options !== 'object') { } else if (!IS_OBJECT(options)) {
throw new TypeError('Bad arguments'); throw new TypeError('Bad arguments');
} }
@ -926,7 +923,7 @@ fs.writeFile = function(path, data, options, callback) {
if (openErr) { if (openErr) {
if (callback) callback(openErr); if (callback) callback(openErr);
} else { } else {
var buffer = Buffer.isBuffer(data) ? data : new Buffer('' + data, var buffer = IS_BUFFER(data) ? data : new Buffer('' + data,
options.encoding || 'utf8'); options.encoding || 'utf8');
var position = /a/.test(flag) ? null : 0; var position = /a/.test(flag) ? null : 0;
writeAll(fd, buffer, 0, buffer.length, position, callback); writeAll(fd, buffer, 0, buffer.length, position, callback);
@ -937,9 +934,9 @@ fs.writeFile = function(path, data, options, callback) {
fs.writeFileSync = function(path, data, options) { fs.writeFileSync = function(path, data, options) {
if (!options) { if (!options) {
options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' }; options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' };
} else if (typeof options === 'string') { } else if (IS_STRING(options)) {
options = { encoding: options, mode: 438, flag: 'w' }; options = { encoding: options, mode: 438, flag: 'w' };
} else if (typeof options !== 'object') { } else if (!IS_OBJECT(options)) {
throw new TypeError('Bad arguments'); throw new TypeError('Bad arguments');
} }
@ -947,7 +944,7 @@ fs.writeFileSync = function(path, data, options) {
var flag = options.flag || 'w'; var flag = options.flag || 'w';
var fd = fs.openSync(path, flag, options.mode); var fd = fs.openSync(path, flag, options.mode);
if (!Buffer.isBuffer(data)) { if (!IS_BUFFER(data)) {
data = new Buffer('' + data, options.encoding || 'utf8'); data = new Buffer('' + data, options.encoding || 'utf8');
} }
var written = 0; var written = 0;
@ -966,13 +963,13 @@ fs.writeFileSync = function(path, data, options) {
fs.appendFile = function(path, data, options, callback_) { fs.appendFile = function(path, data, options, callback_) {
var callback = maybeCallback(arguments[arguments.length - 1]); var callback = maybeCallback(arguments[arguments.length - 1]);
if (typeof options === 'function' || !options) { if (IS_FUNCTION(options) || !options) {
options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' }; options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' };
} else if (typeof options === 'string') { } else if (IS_STRING(options)) {
options = { encoding: options, mode: 438, flag: 'a' }; options = { encoding: options, mode: 438, flag: 'a' };
} else if (!options) { } else if (!options) {
options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' }; options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' };
} else if (typeof options !== 'object') { } else if (!IS_OBJECT(options)) {
throw new TypeError('Bad arguments'); throw new TypeError('Bad arguments');
} }
@ -984,9 +981,9 @@ fs.appendFile = function(path, data, options, callback_) {
fs.appendFileSync = function(path, data, options) { fs.appendFileSync = function(path, data, options) {
if (!options) { if (!options) {
options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' }; options = { encoding: 'utf8', mode: 438 /*=0666*/, flag: 'a' };
} else if (typeof options === 'string') { } else if (IS_STRING(options)) {
options = { encoding: options, mode: 438, flag: 'a' }; options = { encoding: options, mode: 438, flag: 'a' };
} else if (typeof options !== 'object') { } else if (!IS_OBJECT(options)) {
throw new TypeError('Bad arguments'); throw new TypeError('Bad arguments');
} }
if (!options.flag) if (!options.flag)
@ -1033,7 +1030,7 @@ fs.watch = function(filename) {
var options; var options;
var listener; var listener;
if ('object' == typeof arguments[1]) { if (IS_OBJECT(arguments[1])) {
options = arguments[1]; options = arguments[1];
listener = arguments[2]; listener = arguments[2];
} else { } else {
@ -1041,7 +1038,7 @@ fs.watch = function(filename) {
listener = arguments[1]; listener = arguments[1];
} }
if (options.persistent === undefined) options.persistent = true; if (IS_UNDEFINED(options.persistent)) options.persistent = true;
watcher = new FSWatcher(); watcher = new FSWatcher();
watcher.start(filename, options.persistent); watcher.start(filename, options.persistent);
@ -1113,7 +1110,7 @@ fs.watchFile = function(filename) {
persistent: true persistent: true
}; };
if ('object' == typeof arguments[1]) { if (IS_OBJECT(arguments[1])) {
options = util._extend(options, arguments[1]); options = util._extend(options, arguments[1]);
listener = arguments[2]; listener = arguments[2];
} else { } else {
@ -1140,7 +1137,7 @@ fs.unwatchFile = function(filename, listener) {
var stat = statWatchers[filename]; var stat = statWatchers[filename];
if (typeof listener === 'function') { if (IS_FUNCTION(listener)) {
stat.removeListener('change', listener); stat.removeListener('change', listener);
} else { } else {
stat.removeAllListeners('change'); stat.removeAllListeners('change');
@ -1249,7 +1246,7 @@ fs.realpathSync = function realpathSync(p, cache) {
linkTarget = seenLinks[id]; linkTarget = seenLinks[id];
} }
} }
if (linkTarget === null) { if (IS_NULL(linkTarget)) {
fs.statSync(base); fs.statSync(base);
linkTarget = fs.readlinkSync(base); linkTarget = fs.readlinkSync(base);
} }
@ -1271,7 +1268,7 @@ fs.realpathSync = function realpathSync(p, cache) {
fs.realpath = function realpath(p, cache, cb) { fs.realpath = function realpath(p, cache, cb) {
if (typeof cb !== 'function') { if (!IS_FUNCTION(cb)) {
cb = maybeCallback(cache); cb = maybeCallback(cache);
cache = null; cache = null;
} }
@ -1432,13 +1429,13 @@ function ReadStream(path, options) {
options.autoClose : true; options.autoClose : true;
this.pos = undefined; this.pos = undefined;
if (this.start !== undefined) { if (!IS_UNDEFINED(this.start)) {
if ('number' !== typeof this.start) { if (!IS_NUMBER(this.start)) {
throw TypeError('start must be a Number'); throw TypeError('start must be a Number');
} }
if (this.end === undefined) { if (IS_UNDEFINED(this.end)) {
this.end = Infinity; this.end = Infinity;
} else if ('number' !== typeof this.end) { } else if (!IS_NUMBER(this.end)) {
throw TypeError('end must be a Number'); throw TypeError('end must be a Number');
} }
@ -1449,7 +1446,7 @@ function ReadStream(path, options) {
this.pos = this.start; this.pos = this.start;
} }
if (typeof this.fd !== 'number') if (!IS_NUMBER(this.fd))
this.open(); this.open();
this.on('end', function() { this.on('end', function() {
@ -1480,7 +1477,7 @@ ReadStream.prototype.open = function() {
}; };
ReadStream.prototype._read = function(n) { ReadStream.prototype._read = function(n) {
if (typeof this.fd !== 'number') if (!IS_NUMBER(this.fd))
return this.once('open', function() { return this.once('open', function() {
this._read(n); this._read(n);
}); });
@ -1501,7 +1498,7 @@ ReadStream.prototype._read = function(n) {
var toRead = Math.min(pool.length - pool.used, n); var toRead = Math.min(pool.length - pool.used, n);
var start = pool.used; var start = pool.used;
if (this.pos !== undefined) if (!IS_UNDEFINED(this.pos))
toRead = Math.min(this.end - this.pos + 1, toRead); toRead = Math.min(this.end - this.pos + 1, toRead);
// already read everything we were supposed to read! // already read everything we were supposed to read!
@ -1514,7 +1511,7 @@ ReadStream.prototype._read = function(n) {
fs.read(this.fd, pool, pool.used, toRead, this.pos, onread); fs.read(this.fd, pool, pool.used, toRead, this.pos, onread);
// move the pool positions, and internal position for reading. // move the pool positions, and internal position for reading.
if (this.pos !== undefined) if (!IS_UNDEFINED(this.pos))
this.pos += toRead; this.pos += toRead;
pool.used += toRead; pool.used += toRead;
@ -1540,7 +1537,7 @@ ReadStream.prototype.destroy = function() {
return; return;
this.destroyed = true; this.destroyed = true;
if ('number' === typeof this.fd) if (IS_NUMBER(this.fd))
this.close(); this.close();
}; };
@ -1549,8 +1546,8 @@ ReadStream.prototype.close = function(cb) {
var self = this; var self = this;
if (cb) if (cb)
this.once('close', cb); this.once('close', cb);
if (this.closed || 'number' !== typeof this.fd) { if (this.closed || !IS_NUMBER(this.fd)) {
if ('number' !== typeof this.fd) { if (!IS_NUMBER(this.fd)) {
this.once('open', close); this.once('open', close);
return; return;
} }
@ -1598,8 +1595,8 @@ function WriteStream(path, options) {
this.pos = undefined; this.pos = undefined;
this.bytesWritten = 0; this.bytesWritten = 0;
if (this.start !== undefined) { if (!IS_UNDEFINED(this.start)) {
if ('number' !== typeof this.start) { if (!IS_NUMBER(this.start)) {
throw TypeError('start must be a Number'); throw TypeError('start must be a Number');
} }
if (this.start < 0) { if (this.start < 0) {
@ -1609,7 +1606,7 @@ function WriteStream(path, options) {
this.pos = this.start; this.pos = this.start;
} }
if ('number' !== typeof this.fd) if (!IS_NUMBER(this.fd))
this.open(); this.open();
// dispose on finish. // dispose on finish.
@ -1634,10 +1631,10 @@ WriteStream.prototype.open = function() {
WriteStream.prototype._write = function(data, encoding, cb) { WriteStream.prototype._write = function(data, encoding, cb) {
if (!Buffer.isBuffer(data)) if (!IS_BUFFER(data))
return this.emit('error', new Error('Invalid data')); return this.emit('error', new Error('Invalid data'));
if (typeof this.fd !== 'number') if (!IS_NUMBER(this.fd))
return this.once('open', function() { return this.once('open', function() {
this._write(data, encoding, cb); this._write(data, encoding, cb);
}); });
@ -1652,7 +1649,7 @@ WriteStream.prototype._write = function(data, encoding, cb) {
cb(); cb();
}); });
if (this.pos !== undefined) if (!IS_UNDEFINED(this.pos))
this.pos += data.length; this.pos += data.length;
}; };
@ -1686,10 +1683,10 @@ SyncWriteStream.prototype.write = function(data, arg1, arg2) {
// parse arguments // parse arguments
if (arg1) { if (arg1) {
if (typeof arg1 === 'string') { if (IS_STRING(arg1)) {
encoding = arg1; encoding = arg1;
cb = arg2; cb = arg2;
} else if (typeof arg1 === 'function') { } else if (IS_FUNCTION(arg1)) {
cb = arg1; cb = arg1;
} else { } else {
throw new Error('bad arg'); throw new Error('bad arg');
@ -1698,7 +1695,7 @@ SyncWriteStream.prototype.write = function(data, arg1, arg2) {
assertEncoding(encoding); assertEncoding(encoding);
// Change strings to buffers. SLOW // Change strings to buffers. SLOW
if (typeof data == 'string') { if (IS_STRING(data)) {
data = new Buffer(data, encoding); data = new Buffer(data, encoding);
} }

12
lib/https.js

@ -60,21 +60,21 @@ exports.createServer = function(opts, requestListener) {
// HTTPS agents. // HTTPS agents.
function createConnection(port, host, options) { function createConnection(port, host, options) {
if (typeof port === 'object') { if (IS_OBJECT(port)) {
options = port; options = port;
} else if (typeof host === 'object') { } else if (IS_OBJECT(host)) {
options = host; options = host;
} else if (typeof options === 'object') { } else if (IS_OBJECT(options)) {
options = options; options = options;
} else { } else {
options = {}; options = {};
} }
if (typeof port === 'number') { if (IS_NUMBER(port)) {
options.port = port; options.port = port;
} }
if (typeof host === 'string') { if (IS_STRING(host)) {
options.host = host; options.host = host;
} }
@ -115,7 +115,7 @@ Agent.prototype.getName = function(options) {
name += options.pfx; name += options.pfx;
name += ':'; name += ':';
if (options.rejectUnauthorized !== undefined) if (!IS_UNDEFINED(options.rejectUnauthorized))
name += options.rejectUnauthorized; name += options.rejectUnauthorized;
return name; return name;

2
lib/module.js

@ -352,7 +352,7 @@ Module.prototype.load = function(filename) {
Module.prototype.require = function(path) { Module.prototype.require = function(path) {
assert(typeof path === 'string', 'path must be a string'); assert(IS_STRING(path), 'path must be a string');
assert(path, 'missing path'); assert(path, 'missing path');
return Module._load(path, this); return Module._load(path, this);
}; };

66
lib/net.js

@ -57,7 +57,7 @@ function createHandle(fd) {
var debug = util.debuglog('net'); var debug = util.debuglog('net');
function isPipeName(s) { function isPipeName(s) {
return typeof s === 'string' && toNumber(s) === false; return IS_STRING(s) && toNumber(s) === false;
} }
@ -90,7 +90,7 @@ exports.connect = exports.createConnection = function() {
function normalizeConnectArgs(args) { function normalizeConnectArgs(args) {
var options = {}; var options = {};
if (typeof args[0] === 'object') { if (IS_OBJECT(args[0])) {
// connect(options, [cb]) // connect(options, [cb])
options = args[0]; options = args[0];
} else if (isPipeName(args[0])) { } else if (isPipeName(args[0])) {
@ -99,13 +99,13 @@ function normalizeConnectArgs(args) {
} else { } else {
// connect(port, [host], [cb]) // connect(port, [host], [cb])
options.port = args[0]; options.port = args[0];
if (typeof args[1] === 'string') { if (IS_STRING(args[1])) {
options.host = args[1]; options.host = args[1];
} }
} }
var cb = args[args.length - 1]; var cb = args[args.length - 1];
return (typeof cb === 'function') ? [options, cb] : [options]; return IS_FUNCTION(cb) ? [options, cb] : [options];
} }
exports._normalizeConnectArgs = normalizeConnectArgs; exports._normalizeConnectArgs = normalizeConnectArgs;
@ -135,20 +135,16 @@ function Socket(options) {
this._hadError = false; this._hadError = false;
this._handle = null; this._handle = null;
switch (typeof options) { if (IS_NUMBER(options))
case 'number': options = { fd: options }; // Legacy interface.
options = { fd: options }; // Legacy interface. else if (IS_UNDEFINED(options))
break; options = {};
case 'undefined':
options = {};
break;
}
stream.Duplex.call(this, options); stream.Duplex.call(this, options);
if (options.handle) { if (options.handle) {
this._handle = options.handle; // private this._handle = options.handle; // private
} else if (typeof options.fd !== 'undefined') { } else if (!IS_UNDEFINED(options.fd)) {
this._handle = createHandle(options.fd); this._handle = createHandle(options.fd);
this._handle.open(options.fd); this._handle.open(options.fd);
this.readable = options.readable !== false; this.readable = options.readable !== false;
@ -263,7 +259,7 @@ function onSocketEnd() {
// of the other side sending a FIN. The standard 'write after end' // of the other side sending a FIN. The standard 'write after end'
// is overly vague, and makes it seem like the user's code is to blame. // is overly vague, and makes it seem like the user's code is to blame.
function writeAfterFIN(chunk, encoding, cb) { function writeAfterFIN(chunk, encoding, cb) {
if (typeof encoding === 'function') { if (IS_FUNCTION(encoding)) {
cb = encoding; cb = encoding;
encoding = null; encoding = null;
} }
@ -273,7 +269,7 @@ function writeAfterFIN(chunk, encoding, cb) {
var self = this; var self = this;
// TODO: defer error events consistently everywhere, not just the cb // TODO: defer error events consistently everywhere, not just the cb
self.emit('error', er); self.emit('error', er);
if (typeof cb === 'function') { if (IS_FUNCTION(cb)) {
process.nextTick(function() { process.nextTick(function() {
cb(er); cb(er);
}); });
@ -326,7 +322,7 @@ Socket.prototype._onTimeout = function() {
Socket.prototype.setNoDelay = function(enable) { Socket.prototype.setNoDelay = function(enable) {
// backwards compatibility: assume true when `enable` is omitted // backwards compatibility: assume true when `enable` is omitted
if (this._handle && this._handle.setNoDelay) if (this._handle && this._handle.setNoDelay)
this._handle.setNoDelay(typeof enable === 'undefined' ? true : !!enable); this._handle.setNoDelay(IS_UNDEFINED(enable) ? true : !!enable);
}; };
@ -605,7 +601,7 @@ Socket.prototype.__defineGetter__('localPort', function() {
Socket.prototype.write = function(chunk, encoding, cb) { Socket.prototype.write = function(chunk, encoding, cb) {
if (typeof chunk !== 'string' && !Buffer.isBuffer(chunk)) if (!IS_STRING(chunk) && !IS_BUFFER(chunk))
throw new TypeError('invalid data'); throw new TypeError('invalid data');
return stream.Duplex.prototype.write.apply(this, arguments); return stream.Duplex.prototype.write.apply(this, arguments);
}; };
@ -650,7 +646,7 @@ Socket.prototype._writeGeneric = function(writev, data, encoding, cb) {
// Retain chunks // Retain chunks
if (err === 0) req._chunks = chunks; if (err === 0) req._chunks = chunks;
} else { } else {
var enc = Buffer.isBuffer(data) ? 'buffer' : encoding; var enc = IS_BUFFER(data) ? 'buffer' : encoding;
err = createWriteReq(req, this._handle, data, enc); err = createWriteReq(req, this._handle, data, enc);
} }
@ -732,14 +728,14 @@ Socket.prototype.__defineGetter__('bytesWritten', function() {
encoding = this._pendingEncoding; encoding = this._pendingEncoding;
state.buffer.forEach(function(el) { state.buffer.forEach(function(el) {
if (Buffer.isBuffer(el.chunk)) if (IS_BUFFER(el.chunk))
bytes += el.chunk.length; bytes += el.chunk.length;
else else
bytes += Buffer.byteLength(el.chunk, el.encoding); bytes += Buffer.byteLength(el.chunk, el.encoding);
}); });
if (data) { if (data) {
if (Buffer.isBuffer(data)) if (IS_BUFFER(data))
bytes += data.length; bytes += data.length;
else else
bytes += Buffer.byteLength(data, encoding); bytes += Buffer.byteLength(data, encoding);
@ -817,7 +813,7 @@ Socket.prototype.connect = function(options, cb) {
if (this.write !== Socket.prototype.write) if (this.write !== Socket.prototype.write)
this.write = Socket.prototype.write; this.write = Socket.prototype.write;
if (typeof options !== 'object') { if (!IS_OBJECT(options)) {
// Old API: // Old API:
// connect(port, [host], [cb]) // connect(port, [host], [cb])
// connect(path, [cb]); // connect(path, [cb]);
@ -844,7 +840,7 @@ Socket.prototype.connect = function(options, cb) {
initSocketHandle(this); initSocketHandle(this);
} }
if (typeof cb === 'function') { if (IS_FUNCTION(cb)) {
self.once('connect', cb); self.once('connect', cb);
} }
@ -952,13 +948,13 @@ function Server(/* [ options, ] listener */) {
var options; var options;
if (typeof arguments[0] == 'function') { if (IS_FUNCTION(arguments[0])) {
options = {}; options = {};
self.on('connection', arguments[0]); self.on('connection', arguments[0]);
} else { } else {
options = arguments[0] || {}; options = arguments[0] || {};
if (typeof arguments[1] == 'function') { if (IS_FUNCTION(arguments[1])) {
self.on('connection', arguments[1]); self.on('connection', arguments[1]);
} }
} }
@ -998,7 +994,7 @@ var createServerHandle = exports._createServerHandle =
// assign handle in listen, and clean up if bind or listen fails // assign handle in listen, and clean up if bind or listen fails
var handle; var handle;
if (typeof fd === 'number' && fd >= 0) { if (IS_NUMBER(fd) && fd >= 0) {
try { try {
handle = createHandle(fd); handle = createHandle(fd);
} }
@ -1051,7 +1047,7 @@ Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
if (!self._handle) { if (!self._handle) {
debug('_listen2: create a handle'); debug('_listen2: create a handle');
var rval = createServerHandle(address, port, addressType, fd); var rval = createServerHandle(address, port, addressType, fd);
if (typeof rval === 'number') { if (IS_NUMBER(rval)) {
var error = errnoException(rval, 'listen'); var error = errnoException(rval, 'listen');
process.nextTick(function() { process.nextTick(function() {
self.emit('error', error); self.emit('error', error);
@ -1126,7 +1122,7 @@ Server.prototype.listen = function() {
var self = this; var self = this;
var lastArg = arguments[arguments.length - 1]; var lastArg = arguments[arguments.length - 1];
if (typeof lastArg == 'function') { if (IS_FUNCTION(lastArg)) {
self.once('listening', lastArg); self.once('listening', lastArg);
} }
@ -1138,11 +1134,11 @@ Server.prototype.listen = function() {
var TCP = process.binding('tcp_wrap').TCP; var TCP = process.binding('tcp_wrap').TCP;
if (arguments.length == 0 || typeof arguments[0] == 'function') { if (arguments.length == 0 || IS_FUNCTION(arguments[0])) {
// Bind to a random port. // Bind to a random port.
listen(self, '0.0.0.0', 0, null, backlog); listen(self, '0.0.0.0', 0, null, backlog);
} else if (arguments[0] && typeof arguments[0] === 'object') { } else if (arguments[0] && IS_OBJECT(arguments[0])) {
var h = arguments[0]; var h = arguments[0];
if (h._handle) { if (h._handle) {
h = h._handle; h = h._handle;
@ -1152,7 +1148,7 @@ Server.prototype.listen = function() {
if (h instanceof TCP) { if (h instanceof TCP) {
self._handle = h; self._handle = h;
listen(self, null, -1, -1, backlog); listen(self, null, -1, -1, backlog);
} else if (typeof h.fd === 'number' && h.fd >= 0) { } else if (IS_NUMBER(h.fd) && h.fd >= 0) {
listen(self, null, null, null, backlog, h.fd); listen(self, null, null, null, backlog, h.fd);
} else { } else {
throw new Error('Invalid listen argument: ' + h); throw new Error('Invalid listen argument: ' + h);
@ -1162,9 +1158,9 @@ Server.prototype.listen = function() {
var pipeName = self._pipeName = arguments[0]; var pipeName = self._pipeName = arguments[0];
listen(self, pipeName, -1, -1, backlog); listen(self, pipeName, -1, -1, backlog);
} else if (typeof arguments[1] == 'undefined' || } else if (IS_UNDEFINED(arguments[1]) ||
typeof arguments[1] == 'function' || IS_FUNCTION(arguments[1]) ||
typeof arguments[1] == 'number') { IS_NUMBER(arguments[1])) {
// The first argument is the port, no IP given. // The first argument is the port, no IP given.
listen(self, '0.0.0.0', port, 4, backlog); listen(self, '0.0.0.0', port, 4, backlog);
@ -1351,11 +1347,11 @@ if (process.platform === 'win32') {
var simultaneousAccepts; var simultaneousAccepts;
exports._setSimultaneousAccepts = function(handle) { exports._setSimultaneousAccepts = function(handle) {
if (typeof handle === 'undefined') { if (IS_UNDEFINED(handle)) {
return; return;
} }
if (typeof simultaneousAccepts === 'undefined') { if (IS_UNDEFINED(simultaneousAccepts)) {
simultaneousAccepts = (process.env.NODE_MANY_ACCEPTS && simultaneousAccepts = (process.env.NODE_MANY_ACCEPTS &&
process.env.NODE_MANY_ACCEPTS !== '0'); process.env.NODE_MANY_ACCEPTS !== '0');
} }

10
lib/path.js

@ -112,7 +112,7 @@ if (isWindows) {
} }
// Skip empty and invalid entries // Skip empty and invalid entries
if (typeof path !== 'string') { if (!IS_STRING(path)) {
throw new TypeError('Arguments to path.resolve must be strings'); throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) { } else if (!path) {
continue; continue;
@ -214,7 +214,7 @@ if (isWindows) {
// windows version // windows version
exports.join = function() { exports.join = function() {
function f(p) { function f(p) {
if (typeof p !== 'string') { if (!IS_STRING(p)) {
throw new TypeError('Arguments to path.join must be strings'); throw new TypeError('Arguments to path.join must be strings');
} }
return p; return p;
@ -323,7 +323,7 @@ if (isWindows) {
var path = (i >= 0) ? arguments[i] : process.cwd(); var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries // Skip empty and invalid entries
if (typeof path !== 'string') { if (!IS_STRING(path)) {
throw new TypeError('Arguments to path.resolve must be strings'); throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) { } else if (!path) {
continue; continue;
@ -374,7 +374,7 @@ if (isWindows) {
exports.join = function() { exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0); var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(paths.filter(function(p, index) { return exports.normalize(paths.filter(function(p, index) {
if (typeof p !== 'string') { if (!IS_STRING(p)) {
throw new TypeError('Arguments to path.join must be strings'); throw new TypeError('Arguments to path.join must be strings');
} }
return p; return p;
@ -476,7 +476,7 @@ exports.existsSync = util.deprecate(function(path) {
if (isWindows) { if (isWindows) {
exports._makeLong = function(path) { exports._makeLong = function(path) {
// Note: this will *probably* throw somewhere. // Note: this will *probably* throw somewhere.
if (typeof path !== 'string') if (!IS_STRING(path))
return path; return path;
if (!path) { if (!path) {

32
lib/querystring.js

@ -114,33 +114,27 @@ QueryString.escape = function(str) {
}; };
var stringifyPrimitive = function(v) { var stringifyPrimitive = function(v) {
switch (typeof v) { if (IS_STRING(v))
case 'string': return v;
return v; if (IS_BOOLEAN(v))
return v ? 'true' : 'false';
case 'boolean': if (IS_NUMBER(v))
return v ? 'true' : 'false'; return isFinite(v) ? v : '';
return '';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
}; };
QueryString.stringify = QueryString.encode = function(obj, sep, eq, name) { QueryString.stringify = QueryString.encode = function(obj, sep, eq, name) {
sep = sep || '&'; sep = sep || '&';
eq = eq || '='; eq = eq || '=';
if (obj === null) { if (IS_NULL(obj)) {
obj = undefined; obj = undefined;
} }
if (typeof obj === 'object') { if (IS_OBJECT(obj)) {
return Object.keys(obj).map(function(k) { return Object.keys(obj).map(function(k) {
var ks = QueryString.escape(stringifyPrimitive(k)) + eq; var ks = QueryString.escape(stringifyPrimitive(k)) + eq;
if (Array.isArray(obj[k])) { if (IS_ARRAY(obj[k])) {
return obj[k].map(function(v) { return obj[k].map(function(v) {
return ks + QueryString.escape(stringifyPrimitive(v)); return ks + QueryString.escape(stringifyPrimitive(v));
}).join(sep); }).join(sep);
@ -162,7 +156,7 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) {
eq = eq || '='; eq = eq || '=';
var obj = {}; var obj = {};
if (typeof qs !== 'string' || qs.length === 0) { if (!IS_STRING(qs) || qs.length === 0) {
return obj; return obj;
} }
@ -170,7 +164,7 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) {
qs = qs.split(sep); qs = qs.split(sep);
var maxKeys = 1000; var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') { if (options && IS_NUMBER(options.maxKeys)) {
maxKeys = options.maxKeys; maxKeys = options.maxKeys;
} }
@ -203,7 +197,7 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) {
if (!hasOwnProperty(obj, k)) { if (!hasOwnProperty(obj, k)) {
obj[k] = v; obj[k] = v;
} else if (Array.isArray(obj[k])) { } else if (IS_ARRAY(obj[k])) {
obj[k].push(v); obj[k].push(v);
} else { } else {
obj[k] = [obj[k], v]; obj[k] = [obj[k], v];

24
lib/readline.js

@ -63,13 +63,13 @@ function Interface(input, output, completer, terminal) {
completer = completer || function() { return []; }; completer = completer || function() { return []; };
if (typeof completer !== 'function') { if (!IS_FUNCTION(completer)) {
throw new TypeError('Argument \'completer\' must be a function'); throw new TypeError('Argument \'completer\' must be a function');
} }
// backwards compat; check the isTTY prop of the output stream // backwards compat; check the isTTY prop of the output stream
// when `terminal` was not specified // when `terminal` was not specified
if (typeof terminal == 'undefined') { if (IS_UNDEFINED(terminal)) {
terminal = !!output.isTTY; terminal = !!output.isTTY;
} }
@ -154,7 +154,7 @@ Interface.prototype.setPrompt = function(prompt) {
Interface.prototype._setRawMode = function(mode) { Interface.prototype._setRawMode = function(mode) {
if (typeof this.input.setRawMode === 'function') { if (IS_FUNCTION(this.input.setRawMode)) {
return this.input.setRawMode(mode); return this.input.setRawMode(mode);
} }
}; };
@ -172,7 +172,7 @@ Interface.prototype.prompt = function(preserveCursor) {
Interface.prototype.question = function(query, cb) { Interface.prototype.question = function(query, cb) {
if (typeof cb === 'function') { if (IS_FUNCTION(cb)) {
if (this._questionCallback) { if (this._questionCallback) {
this.prompt(); this.prompt();
} else { } else {
@ -290,7 +290,7 @@ Interface.prototype.write = function(d, key) {
// \r\n, \n, or \r followed by something other than \n // \r\n, \n, or \r followed by something other than \n
var lineEnding = /\r?\n|\r(?!\n)/; var lineEnding = /\r?\n|\r(?!\n)/;
Interface.prototype._normalWrite = function(b) { Interface.prototype._normalWrite = function(b) {
if (b === undefined) { if (IS_UNDEFINED(b)) {
return; return;
} }
var string = this._decoder.write(b); var string = this._decoder.write(b);
@ -843,7 +843,7 @@ Interface.prototype._ttyWrite = function(s, key) {
break; break;
default: default:
if (Buffer.isBuffer(s)) if (IS_BUFFER(s))
s = s.toString('utf-8'); s = s.toString('utf-8');
if (s) { if (s) {
@ -944,8 +944,8 @@ function emitKey(stream, s) {
}, },
parts; parts;
if (Buffer.isBuffer(s)) { if (IS_BUFFER(s)) {
if (s[0] > 127 && s[1] === undefined) { if (s[0] > 127 && IS_UNDEFINED(s[1])) {
s[0] -= 128; s[0] -= 128;
s = '\x1b' + s.toString(stream.encoding || 'utf-8'); s = '\x1b' + s.toString(stream.encoding || 'utf-8');
} else { } else {
@ -1124,7 +1124,7 @@ function emitKey(stream, s) {
} }
// Don't emit a key if no name was found // Don't emit a key if no name was found
if (key.name === undefined) { if (IS_UNDEFINED(key.name)) {
key = undefined; key = undefined;
} }
@ -1143,13 +1143,13 @@ function emitKey(stream, s) {
*/ */
function cursorTo(stream, x, y) { function cursorTo(stream, x, y) {
if (typeof x !== 'number' && typeof y !== 'number') if (!IS_NUMBER(x) && !IS_NUMBER(y))
return; return;
if (typeof x !== 'number') if (!IS_NUMBER(x))
throw new Error("Can't set cursor row without also setting it's column"); throw new Error("Can't set cursor row without also setting it's column");
if (typeof y !== 'number') { if (!IS_NUMBER(y)) {
stream.write('\x1b[' + (x + 1) + 'G'); stream.write('\x1b[' + (x + 1) + 'G');
} else { } else {
stream.write('\x1b[' + (y + 1) + ';' + (x + 1) + 'H'); stream.write('\x1b[' + (y + 1) + ';' + (x + 1) + 'H');

28
lib/repl.js

@ -83,7 +83,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
EventEmitter.call(this); EventEmitter.call(this);
var options, input, output, dom; var options, input, output, dom;
if (typeof prompt == 'object') { if (IS_OBJECT(prompt)) {
// an options object was given // an options object was given
options = prompt; options = prompt;
stream = options.stream || options.socket; stream = options.stream || options.socket;
@ -94,7 +94,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
ignoreUndefined = options.ignoreUndefined; ignoreUndefined = options.ignoreUndefined;
prompt = options.prompt; prompt = options.prompt;
dom = options.domain; dom = options.domain;
} else if (typeof prompt != 'string') { } else if (!IS_STRING(prompt)) {
throw new Error('An options Object, or a prompt String are required'); throw new Error('An options Object, or a prompt String are required');
} else { } else {
options = {}; options = {};
@ -160,7 +160,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
self.resetContext(); self.resetContext();
self.bufferedCommand = ''; self.bufferedCommand = '';
self.prompt = (prompt != undefined ? prompt : '> '); self.prompt = !IS_UNDEFINED(prompt) ? prompt : '> ';
function complete(text, callback) { function complete(text, callback) {
self.complete(text, callback); self.complete(text, callback);
@ -180,7 +180,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
// figure out which "writer" function to use // figure out which "writer" function to use
self.writer = options.writer || exports.writer; self.writer = options.writer || exports.writer;
if (typeof options.useColors === 'undefined') { if (IS_UNDEFINED(options.useColors)) {
options.useColors = rli.terminal; options.useColors = rli.terminal;
} }
self.useColors = !!options.useColors; self.useColors = !!options.useColors;
@ -256,9 +256,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
function(e, ret) { function(e, ret) {
if (e && !isSyntaxError(e)) return finish(e); if (e && !isSyntaxError(e)) return finish(e);
if (typeof ret === 'function' && if (IS_FUNCTION(ret) && /^[\r\n\s]*function/.test(evalCmd) || e) {
/^[\r\n\s]*function/.test(evalCmd) ||
e) {
// Now as statement without parens. // Now as statement without parens.
self.eval(evalCmd, self.context, 'repl', finish); self.eval(evalCmd, self.context, 'repl', finish);
} else { } else {
@ -300,7 +298,7 @@ function REPLServer(prompt, stream, eval_, useGlobal, ignoreUndefined) {
self.bufferedCommand = ''; self.bufferedCommand = '';
// If we got any output - print it (if no error) // If we got any output - print it (if no error)
if (!e && (!self.ignoreUndefined || ret !== undefined)) { if (!e && (!self.ignoreUndefined || !IS_UNDEFINED(ret))) {
self.context._ = ret; self.context._ = ret;
self.outputStream.write(self.writer(ret) + '\n'); self.outputStream.write(self.writer(ret) + '\n');
} }
@ -422,7 +420,7 @@ var simpleExpressionRE =
// getter code. // getter code.
REPLServer.prototype.complete = function(line, callback) { REPLServer.prototype.complete = function(line, callback) {
// There may be local variables to evaluate, try a nested REPL // There may be local variables to evaluate, try a nested REPL
if (this.bufferedCommand != undefined && this.bufferedCommand.length) { if (!IS_UNDEFINED(this.bufferedCommand) && this.bufferedCommand.length) {
// Get a new array of inputed lines // Get a new array of inputed lines
var tmp = this.lines.slice(); var tmp = this.lines.slice();
// Kill off all function declarations to push all local variables into // Kill off all function declarations to push all local variables into
@ -564,7 +562,7 @@ REPLServer.prototype.complete = function(line, callback) {
this.eval('.scope', this.context, 'repl', function(err, globals) { this.eval('.scope', this.context, 'repl', function(err, globals) {
if (err || !globals) { if (err || !globals) {
addStandardGlobals(completionGroups, filter); addStandardGlobals(completionGroups, filter);
} else if (Array.isArray(globals[0])) { } else if (IS_ARRAY(globals[0])) {
// Add grouped globals // Add grouped globals
globals.forEach(function(group) { globals.forEach(function(group) {
completionGroups.push(group); completionGroups.push(group);
@ -581,19 +579,19 @@ REPLServer.prototype.complete = function(line, callback) {
// if (e) console.log(e); // if (e) console.log(e);
if (obj != null) { if (obj != null) {
if (typeof obj === 'object' || typeof obj === 'function') { if (IS_OBJECT(obj) || IS_FUNCTION(obj)) {
memberGroups.push(Object.getOwnPropertyNames(obj)); memberGroups.push(Object.getOwnPropertyNames(obj));
} }
// works for non-objects // works for non-objects
try { try {
var sentinel = 5; var sentinel = 5;
var p; var p;
if (typeof obj === 'object' || typeof obj === 'function') { if (IS_OBJECT(obj) || IS_FUNCTION(obj)) {
p = Object.getPrototypeOf(obj); p = Object.getPrototypeOf(obj);
} else { } else {
p = obj.constructor ? obj.constructor.prototype : null; p = obj.constructor ? obj.constructor.prototype : null;
} }
while (p !== null) { while (!IS_NULL(p)) {
memberGroups.push(Object.getOwnPropertyNames(p)); memberGroups.push(Object.getOwnPropertyNames(p));
p = Object.getPrototypeOf(p); p = Object.getPrototypeOf(p);
// Circular refs possible? Let's guard against that. // Circular refs possible? Let's guard against that.
@ -692,9 +690,9 @@ REPLServer.prototype.parseREPLKeyword = function(keyword, rest) {
REPLServer.prototype.defineCommand = function(keyword, cmd) { REPLServer.prototype.defineCommand = function(keyword, cmd) {
if (typeof cmd === 'function') { if (IS_FUNCTION(cmd)) {
cmd = {action: cmd}; cmd = {action: cmd};
} else if (typeof cmd.action !== 'function') { } else if (!IS_FUNCTION(cmd.action)) {
throw new Error('bad argument, action must be a function'); throw new Error('bad argument, action must be a function');
} }
this.commands['.' + keyword] = cmd; this.commands['.' + keyword] = cmd;

6
lib/smalloc.js

@ -39,15 +39,15 @@ function alloc(n, obj) {
if (n > kMaxLength) if (n > kMaxLength)
throw new RangeError('n > kMaxLength'); throw new RangeError('n > kMaxLength');
if (Array.isArray(obj)) if (IS_ARRAY(obj))
throw new TypeError('Arrays are not supported'); throw new TypeError('Arrays are not supported');
return smalloc.alloc(obj === undefined ? {} : obj, n); return smalloc.alloc(IS_UNDEFINED(obj) ? {} : obj, n);
} }
function dispose(obj) { function dispose(obj) {
if (obj instanceof Buffer) if (IS_BUFFER(obj))
throw new TypeError('obj cannot be a Buffer'); throw new TypeError('obj cannot be a Buffer');
smalloc.dispose(obj); smalloc.dispose(obj);
} }

2
lib/stream.js

@ -84,7 +84,7 @@ Stream.prototype.pipe = function(dest, options) {
if (didOnEnd) return; if (didOnEnd) return;
didOnEnd = true; didOnEnd = true;
if (typeof dest.destroy === 'function') dest.destroy(); if (IS_FUNCTION(dest.destroy)) dest.destroy();
} }
// don't leave dangling pipes when there are errors. // don't leave dangling pipes when there are errors.

8
lib/tls.js

@ -51,7 +51,7 @@ exports.getCiphers = function() {
// ("\x06spdy/2\x08http/1.1\x08http/1.0") // ("\x06spdy/2\x08http/1.1\x08http/1.0")
exports.convertNPNProtocols = function convertNPNProtocols(NPNProtocols, out) { exports.convertNPNProtocols = function convertNPNProtocols(NPNProtocols, out) {
// If NPNProtocols is Array - translate it into buffer // If NPNProtocols is Array - translate it into buffer
if (Array.isArray(NPNProtocols)) { if (IS_ARRAY(NPNProtocols)) {
var buff = new Buffer(NPNProtocols.reduce(function(p, c) { var buff = new Buffer(NPNProtocols.reduce(function(p, c) {
return p + 1 + Buffer.byteLength(c); return p + 1 + Buffer.byteLength(c);
}, 0)); }, 0));
@ -68,7 +68,7 @@ exports.convertNPNProtocols = function convertNPNProtocols(NPNProtocols, out) {
} }
// If it's already a Buffer - store it // If it's already a Buffer - store it
if (Buffer.isBuffer(NPNProtocols)) { if (IS_BUFFER(NPNProtocols)) {
out.NPNProtocols = NPNProtocols; out.NPNProtocols = NPNProtocols;
} }
}; };
@ -166,7 +166,7 @@ exports.checkServerIdentity = function checkServerIdentity(host, cert) {
// RFC6125 // RFC6125
if (matchCN) { if (matchCN) {
var commonNames = cert.subject.CN; var commonNames = cert.subject.CN;
if (Array.isArray(commonNames)) { if (IS_ARRAY(commonNames)) {
for (var i = 0, k = commonNames.length; i < k; ++i) { for (var i = 0, k = commonNames.length; i < k; ++i) {
dnsNames.push(regexpify(commonNames[i], true)); dnsNames.push(regexpify(commonNames[i], true));
} }
@ -194,7 +194,7 @@ exports.parseCertString = function parseCertString(s) {
var key = parts[i].slice(0, sepIndex); var key = parts[i].slice(0, sepIndex);
var value = parts[i].slice(sepIndex + 1); var value = parts[i].slice(sepIndex + 1);
if (key in out) { if (key in out) {
if (!Array.isArray(out[key])) { if (!IS_ARRAY(out[key])) {
out[key] = [out[key]]; out[key] = [out[key]];
} }
out[key].push(value); out[key].push(value);

17
lib/url.js

@ -94,7 +94,7 @@ var protocolPattern = /^([a-z0-9.+-]+:)/i,
querystring = require('querystring'); querystring = require('querystring');
function urlParse(url, parseQueryString, slashesDenoteHost) { function urlParse(url, parseQueryString, slashesDenoteHost) {
if (url && typeof(url) === 'object' && url instanceof Url) return url; if (url && IS_OBJECT(url) && url instanceof Url) return url;
var u = new Url; var u = new Url;
u.parse(url, parseQueryString, slashesDenoteHost); u.parse(url, parseQueryString, slashesDenoteHost);
@ -102,7 +102,7 @@ function urlParse(url, parseQueryString, slashesDenoteHost) {
} }
Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
if (typeof url !== 'string') { if (!IS_STRING(url)) {
throw new TypeError("Parameter 'url' must be a string, not " + typeof url); throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
} }
@ -340,7 +340,7 @@ function urlFormat(obj) {
// If it's an obj, this is a no-op. // If it's an obj, this is a no-op.
// this way, you can call url_format() on strings // this way, you can call url_format() on strings
// to clean up potentially wonky urls. // to clean up potentially wonky urls.
if (typeof(obj) === 'string') obj = urlParse(obj); if (IS_STRING(obj)) obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
return obj.format(); return obj.format();
} }
@ -370,8 +370,7 @@ Url.prototype.format = function() {
} }
} }
if (this.query && typeof this.query === 'object' && if (this.query && IS_OBJECT(this.query) && Object.keys(this.query).length) {
Object.keys(this.query).length) {
query = querystring.stringify(this.query); query = querystring.stringify(this.query);
} }
@ -414,7 +413,7 @@ function urlResolveObject(source, relative) {
} }
Url.prototype.resolveObject = function(relative) { Url.prototype.resolveObject = function(relative) {
if (typeof relative === 'string') { if (IS_STRING(relative)) {
var rel = new Url(); var rel = new Url();
rel.parse(relative, false, true); rel.parse(relative, false, true);
relative = rel; relative = rel;
@ -554,7 +553,7 @@ Url.prototype.resolveObject = function(relative) {
srcPath = srcPath.concat(relPath); srcPath = srcPath.concat(relPath);
result.search = relative.search; result.search = relative.search;
result.query = relative.query; result.query = relative.query;
} else if (relative.search !== null && relative.search !== undefined) { } else if (!IS_NULL_OR_UNDEFINED(relative.search)) {
// just pull out the search. // just pull out the search.
// like href='?foo'. // like href='?foo'.
// Put this after the other two cases because it simplifies the booleans // Put this after the other two cases because it simplifies the booleans
@ -573,7 +572,7 @@ Url.prototype.resolveObject = function(relative) {
result.search = relative.search; result.search = relative.search;
result.query = relative.query; result.query = relative.query;
//to support http.request //to support http.request
if (result.pathname !== null || result.search !== null) { if (!IS_NULL(result.pathname) || !IS_NULL(result.search)) {
result.path = (result.pathname ? result.pathname : '') + result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : ''); (result.search ? result.search : '');
} }
@ -667,7 +666,7 @@ Url.prototype.resolveObject = function(relative) {
} }
//to support request.http //to support request.http
if (result.pathname !== null || result.search !== null) { if (!IS_NULL(result.pathname) || !IS_NULL(result.search)) {
result.path = (result.pathname ? result.pathname : '') + result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : ''); (result.search ? result.search : '');
} }

71
lib/util.js

@ -21,7 +21,7 @@
var formatRegExp = /%[sdj%]/g; var formatRegExp = /%[sdj%]/g;
exports.format = function(f) { exports.format = function(f) {
if (typeof f !== 'string') { if (!IS_STRING(f)) {
var objects = []; var objects = [];
for (var i = 0; i < arguments.length; i++) { for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i])); objects.push(inspect(arguments[i]));
@ -44,7 +44,7 @@ exports.format = function(f) {
} }
}); });
for (var x = args[i]; i < len; x = args[++i]) { for (var x = args[i]; i < len; x = args[++i]) {
if (x === null || typeof x !== 'object') { if (IS_NULL(x) || !IS_OBJECT(x)) {
str += ' ' + x; str += ' ' + x;
} else { } else {
str += ' ' + inspect(x); str += ' ' + inspect(x);
@ -117,7 +117,7 @@ function inspect(obj, opts) {
// legacy... // legacy...
if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3]; if (arguments.length >= 4) ctx.colors = arguments[3];
if (typeof opts === 'boolean') { if (IS_BOOLEAN(opts)) {
// legacy... // legacy...
ctx.showHidden = opts; ctx.showHidden = opts;
} else if (opts) { } else if (opts) {
@ -125,10 +125,10 @@ function inspect(obj, opts) {
exports._extend(ctx, opts); exports._extend(ctx, opts);
} }
// set default options // set default options
if (typeof ctx.showHidden === 'undefined') ctx.showHidden = false; if (IS_UNDEFINED(ctx.showHidden)) ctx.showHidden = false;
if (typeof ctx.depth === 'undefined') ctx.depth = 2; if (IS_UNDEFINED(ctx.depth)) ctx.depth = 2;
if (typeof ctx.colors === 'undefined') ctx.colors = false; if (IS_UNDEFINED(ctx.colors)) ctx.colors = false;
if (typeof ctx.customInspect === 'undefined') ctx.customInspect = true; if (IS_UNDEFINED(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor; if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth); return formatValue(ctx, obj, ctx.depth);
} }
@ -197,13 +197,15 @@ function arrayToHash(array) {
function formatValue(ctx, value, recurseTimes) { function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions. // Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it // Check that value is an object with an inspect function on it
if (ctx.customInspect && value && typeof value.inspect === 'function' && if (ctx.customInspect &&
value &&
IS_FUNCTION(value.inspect) &&
// Filter out the util module, it's inspect function is special // Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect && value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check. // Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) { !(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes); var ret = value.inspect(recurseTimes);
if ('string' !== typeof ret) { if (!IS_STRING(ret)) {
ret = formatValue(ctx, ret, recurseTimes); ret = formatValue(ctx, ret, recurseTimes);
} }
return ret; return ret;
@ -225,7 +227,7 @@ function formatValue(ctx, value, recurseTimes) {
// Some type of object without properties can be shortcutted. // Some type of object without properties can be shortcutted.
if (keys.length === 0) { if (keys.length === 0) {
if (typeof value === 'function') { if (IS_FUNCTION(value)) {
var name = value.name ? ': ' + value.name : ''; var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special'); return ctx.stylize('[Function' + name + ']', 'special');
} }
@ -249,7 +251,7 @@ function formatValue(ctx, value, recurseTimes) {
} }
// Make functions say that they are functions // Make functions say that they are functions
if (typeof value === 'function') { if (IS_FUNCTION(value)) {
var n = value.name ? ': ' + value.name : ''; var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']'; base = ' [Function' + n + ']';
} }
@ -299,26 +301,21 @@ function formatValue(ctx, value, recurseTimes) {
function formatPrimitive(ctx, value) { function formatPrimitive(ctx, value) {
switch (typeof value) { if (IS_UNDEFINED(value))
case 'undefined': return ctx.stylize('undefined', 'undefined');
return ctx.stylize('undefined', 'undefined'); if (IS_STRING(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
case 'string': .replace(/'/g, "\\'")
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/\\"/g, '"') + '\'';
.replace(/'/g, "\\'") return ctx.stylize(simple, 'string');
.replace(/\\"/g, '"') + '\''; }
return ctx.stylize(simple, 'string'); if (IS_NUMBER(value))
return ctx.stylize('' + value, 'number');
case 'number': if (IS_BOOLEAN(value))
return ctx.stylize('' + value, 'number'); return ctx.stylize('' + value, 'boolean');
case 'boolean':
return ctx.stylize('' + value, 'boolean');
}
// For some reason typeof null is "object", so special case here. // For some reason typeof null is "object", so special case here.
if (value === null) { if (IS_NULL(value))
return ctx.stylize('null', 'null'); return ctx.stylize('null', 'null');
}
} }
@ -366,7 +363,7 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
} }
if (!str) { if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) { if (ctx.seen.indexOf(desc.value) < 0) {
if (recurseTimes === null) { if (IS_NULL(recurseTimes)) {
str = formatValue(ctx, desc.value, null); str = formatValue(ctx, desc.value, null);
} else { } else {
str = formatValue(ctx, desc.value, recurseTimes - 1); str = formatValue(ctx, desc.value, recurseTimes - 1);
@ -386,7 +383,7 @@ function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
str = ctx.stylize('[Circular]', 'special'); str = ctx.stylize('[Circular]', 'special');
} }
} }
if (typeof name === 'undefined') { if (IS_UNDEFINED(name)) {
if (array && key.match(/^\d+$/)) { if (array && key.match(/^\d+$/)) {
return str; return str;
} }
@ -430,25 +427,25 @@ function reduceToSingleString(output, base, braces) {
// NOTE: These type checking functions intentionally don't use `instanceof` // NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`. // because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) { function isArray(ar) {
return Array.isArray(ar); return IS_ARRAY(ar);
} }
exports.isArray = isArray; exports.isArray = isArray;
function isRegExp(re) { function isRegExp(re) {
return typeof re === 'object' && objectToString(re) === '[object RegExp]'; return IS_OBJECT(re) && objectToString(re) === '[object RegExp]';
} }
exports.isRegExp = isRegExp; exports.isRegExp = isRegExp;
function isDate(d) { function isDate(d) {
return typeof d === 'object' && objectToString(d) === '[object Date]'; return IS_OBJECT(d) && objectToString(d) === '[object Date]';
} }
exports.isDate = isDate; exports.isDate = isDate;
function isError(e) { function isError(e) {
return typeof e === 'object' && objectToString(e) === '[object Error]'; return IS_OBJECT(e) && objectToString(e) === '[object Error]';
} }
exports.isError = isError; exports.isError = isError;
@ -509,7 +506,7 @@ exports.inherits = function(ctor, superCtor) {
exports._extend = function(origin, add) { exports._extend = function(origin, add) {
// Don't do anything if add isn't an object // Don't do anything if add isn't an object
if (!add || typeof add !== 'object') return origin; if (!add || !IS_OBJECT(add)) return origin;
var keys = Object.keys(add); var keys = Object.keys(add);
var i = keys.length; var i = keys.length;
@ -604,7 +601,7 @@ exports.pump = exports.deprecate(function(readStream, writeStream, callback) {
var uv; var uv;
exports._errnoException = function(err, syscall) { exports._errnoException = function(err, syscall) {
if (typeof uv === 'undefined') uv = process.binding('uv'); if (IS_UNDEFINED(uv)) uv = process.binding('uv');
var errname = uv.errname(err); var errname = uv.errname(err);
var e = new Error(syscall + ' ' + errname); var e = new Error(syscall + ' ' + errname);
e.code = errname; e.code = errname;

2
lib/vm.js

@ -33,7 +33,7 @@ function Script(code, ctx, filename) {
// bind all methods to this Script object // bind all methods to this Script object
Object.keys(binding.NodeScript.prototype).forEach(function(f) { Object.keys(binding.NodeScript.prototype).forEach(function(f) {
if (typeof binding.NodeScript.prototype[f] === 'function') { if (IS_FUNCTION(binding.NodeScript.prototype[f])) {
this[f] = function() { this[f] = function() {
if (!(this instanceof Script)) { if (!(this instanceof Script)) {
throw new TypeError('invalid call to ' + f); throw new TypeError('invalid call to ' + f);

24
lib/zlib.js

@ -108,7 +108,7 @@ exports.createUnzip = function(o) {
// Convenience methods. // Convenience methods.
// compress/decompress a string or buffer in one step. // compress/decompress a string or buffer in one step.
exports.deflate = function(buffer, opts, callback) { exports.deflate = function(buffer, opts, callback) {
if (typeof opts === 'function') { if (IS_FUNCTION(opts)) {
callback = opts; callback = opts;
opts = {}; opts = {};
} }
@ -116,7 +116,7 @@ exports.deflate = function(buffer, opts, callback) {
}; };
exports.gzip = function(buffer, opts, callback) { exports.gzip = function(buffer, opts, callback) {
if (typeof opts === 'function') { if (IS_FUNCTION(opts)) {
callback = opts; callback = opts;
opts = {}; opts = {};
} }
@ -124,7 +124,7 @@ exports.gzip = function(buffer, opts, callback) {
}; };
exports.deflateRaw = function(buffer, opts, callback) { exports.deflateRaw = function(buffer, opts, callback) {
if (typeof opts === 'function') { if (IS_FUNCTION(opts)) {
callback = opts; callback = opts;
opts = {}; opts = {};
} }
@ -132,7 +132,7 @@ exports.deflateRaw = function(buffer, opts, callback) {
}; };
exports.unzip = function(buffer, opts, callback) { exports.unzip = function(buffer, opts, callback) {
if (typeof opts === 'function') { if (IS_FUNCTION(opts)) {
callback = opts; callback = opts;
opts = {}; opts = {};
} }
@ -140,7 +140,7 @@ exports.unzip = function(buffer, opts, callback) {
}; };
exports.inflate = function(buffer, opts, callback) { exports.inflate = function(buffer, opts, callback) {
if (typeof opts === 'function') { if (IS_FUNCTION(opts)) {
callback = opts; callback = opts;
opts = {}; opts = {};
} }
@ -148,7 +148,7 @@ exports.inflate = function(buffer, opts, callback) {
}; };
exports.gunzip = function(buffer, opts, callback) { exports.gunzip = function(buffer, opts, callback) {
if (typeof opts === 'function') { if (IS_FUNCTION(opts)) {
callback = opts; callback = opts;
opts = {}; opts = {};
} }
@ -156,7 +156,7 @@ exports.gunzip = function(buffer, opts, callback) {
}; };
exports.inflateRaw = function(buffer, opts, callback) { exports.inflateRaw = function(buffer, opts, callback) {
if (typeof opts === 'function') { if (IS_FUNCTION(opts)) {
callback = opts; callback = opts;
opts = {}; opts = {};
} }
@ -305,7 +305,7 @@ function Zlib(opts, mode) {
} }
if (opts.dictionary) { if (opts.dictionary) {
if (!Buffer.isBuffer(opts.dictionary)) { if (!IS_BUFFER(opts.dictionary)) {
throw new Error('Invalid dictionary: it should be a Buffer instance'); throw new Error('Invalid dictionary: it should be a Buffer instance');
} }
} }
@ -327,10 +327,10 @@ function Zlib(opts, mode) {
}; };
var level = exports.Z_DEFAULT_COMPRESSION; var level = exports.Z_DEFAULT_COMPRESSION;
if (typeof opts.level === 'number') level = opts.level; if (IS_NUMBER(opts.level)) level = opts.level;
var strategy = exports.Z_DEFAULT_STRATEGY; var strategy = exports.Z_DEFAULT_STRATEGY;
if (typeof opts.strategy === 'number') strategy = opts.strategy; if (IS_NUMBER(opts.strategy)) strategy = opts.strategy;
this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
level, level,
@ -390,7 +390,7 @@ Zlib.prototype._flush = function(callback) {
Zlib.prototype.flush = function(kind, callback) { Zlib.prototype.flush = function(kind, callback) {
var ws = this._writableState; var ws = this._writableState;
if (typeof kind === 'function' || (kind === undefined && !callback)) { if (IS_FUNCTION(kind) || (IS_UNDEFINED(kind) && !callback)) {
callback = kind; callback = kind;
kind = binding.Z_FULL_FLUSH; kind = binding.Z_FULL_FLUSH;
} }
@ -435,7 +435,7 @@ Zlib.prototype._transform = function(chunk, encoding, cb) {
var ending = ws.ending || ws.ended; var ending = ws.ending || ws.ended;
var last = ending && (!chunk || ws.length === chunk.length); var last = ending && (!chunk || ws.length === chunk.length);
if (chunk !== null && !Buffer.isBuffer(chunk)) if (!IS_NULL(chunk) && !IS_BUFFER(chunk))
return cb(new Error('invalid input')); return cb(new Error('invalid input'));
// If it's the last chunk, or a final flush, we use the Z_FINISH flush flag. // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag.

1
node.gyp

@ -388,6 +388,7 @@
'<(python)', '<(python)',
'tools/js2c.py', 'tools/js2c.py',
'<@(_outputs)', '<@(_outputs)',
'src/macros.py',
'<@(_inputs)', '<@(_inputs)',
], ],
}, },

16
src/macros.py

@ -0,0 +1,16 @@
macro IS_BOOLEAN(arg) = (typeof(arg) === 'boolean');
macro IS_NULL(arg) = (arg === null);
macro IS_NULL_OR_UNDEFINED(arg) = (arg == null);
macro IS_NUMBER(arg) = (typeof(arg) === 'number');
macro IS_STRING(arg) = (typeof(arg) === 'string');
macro IS_SYMBOL(arg) = (typeof(arg) === 'symbol');
macro IS_UNDEFINED(arg) = (typeof(arg) === 'undefined');
# These macros follow the semantics of V8's %_Is*() functions.
macro IS_ARRAY(arg) = (Array.isArray(arg));
macro IS_DATE(arg) = ((arg) instanceof Date);
macro IS_FUNCTION(arg) = (typeof(arg) === 'function');
macro IS_OBJECT(arg) = (typeof(arg) === 'object');
macro IS_REGEXP(arg) = ((arg) instanceof RegExp);
macro IS_BUFFER(arg) = ((arg) instanceof Buffer);
Loading…
Cancel
Save