exports.fires = function fires(promise, error, timeoutMs) { if (!timeoutMs && util.isNumber(error)) { timeoutMs = error; error = null; } if (!error) error = 'timeout'; if (!timeoutMs) timeoutMs = 100; const timeout = timeoutPromise(error, timeoutMs); return Promise.race([ onResolvedOrRejected(promise, () => timeout.clear()), timeout ]); };
function WriteStream(path, options) { if (!(this instanceof WriteStream)) return new WriteStream(path, options); options = options || {}; Writable.call(this, options); this.path = path; this.fd = null; this.fd = options.hasOwnProperty('fd') ? options.fd : null; this.flags = options.hasOwnProperty('flags') ? options.flags : 'w'; this.mode = options.hasOwnProperty('mode') ? options.mode : 438; /*=0666*/ this.start = options.hasOwnProperty('start') ? options.start : undefined; this.pos = undefined; this.bytesWritten = 0; if (!util.isUndefined(this.start)) { if (!util.isNumber(this.start)) { throw TypeError('start must be a Number'); } if (this.start < 0) { throw new Error('start must be >= zero'); } this.pos = this.start; } if (!util.isNumber(this.fd)) this.open(); // dispose on finish. this.once('finish', this.close); }
ReadStream.prototype.close = function(cb) { var self = this; if (cb) this.once('close', cb); if (this.closed || !util.isNumber(this.fd)) { if (!util.isNumber(this.fd)) { this.once('open', close); return; } return process.nextTick(this.emit.bind(this, 'close')); } this.closed = true; close(); function close(fd) { fs.close(fd || self.fd, function(er) { if (er) self.emit('error', er); else self.emit('close'); }); self.fd = null; } };
Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { debug('listen2', address, port, addressType, backlog); var self = this; var alreadyListening = false; // If there is not yet a handle, we need to create one and bind. // In the case of a server sent via IPC, we don't need to do this. if (!self._handle) { debug('_listen2: create a handle'); var rval = createServerHandle(address, port, addressType, fd); if (util.isNumber(rval)) { var error = errnoException(rval, 'listen'); process.nextTick(function() { self.emit('error', error); }); return; } alreadyListening = (process.platform === 'win32'); self._handle = rval; } else { debug('_listen2: have a handle already'); } self._handle.onconnection = onconnection; self._handle.owner = self; var err = 0; if (!alreadyListening) err = _listen(self._handle, backlog); if (err) { var ex = errnoException(err, 'listen'); self._handle.close(); self._handle = null; process.nextTick(function() { self.emit('error', ex); }); return; } // generate connection key, this should be unique to the connection this._connectionKey = addressType + ':' + address + ':' + port; process.nextTick(function() { self.emit('listening'); }); };
function Socket(options) { if (!(this instanceof Socket)) return new Socket(options); this._connecting = false; this._hadError = false; this._handle = null; if (util.isNumber(options)) options = { fd: options }; // Legacy interface. else if (util.isUndefined(options)) options = {}; stream.Duplex.call(this, options); if (options.handle) { this._handle = options.handle; // private } else if (!util.isUndefined(options.fd)) { this._handle = createHandle(options.fd); this._handle.open(options.fd); this.readable = options.readable !== false; this.writable = options.writable !== false; } else { // these will be set once there is a connection this.readable = this.writable = false; } this.onend = null; // shut down the socket when we're finished with it. this.on('finish', onSocketFinish); this.on('_socketEnd', onSocketEnd); initSocketHandle(this); this._pendingData = null; this._pendingEncoding = ''; // handle strings directly this._writableState.decodeStrings = false; // default to *not* allowing half open sockets this.allowHalfOpen = options && options.allowHalfOpen || false; // if we have a handle, then start the flow of data into the // buffer. if not, then this will happen when we connect if (this._handle && options.readable !== false) this.read(0); }
PwmPin.prototype.setEnable = function(enable, callback) { var self = this; if (_binding === null) { throw new Error('Pwm pin is not opened'); } // Check arguments. if (!util.isNumber(enable) && !util.isBoolean(enable)) { throw new TypeError('enable is of type ' + typeof(enable)); } _binding.setEnable(!!enable, function(err) { util.isFunction(callback) && callback.call(self, err); }); };
exports._createSocketHandle = function(address, port, addressType, fd) { // Opening an existing fd is not supported for UDP handles. assert(!util.isNumber(fd) || fd < 0); var handle = newHandle(addressType); if (port || address) { var err = handle.bind(address, port || 0, 0); if (err) { handle.close(); return err; } } return handle; };
function replacer(value) { if (util.isUndefined(value)) { return '' + value; } //console.log(value && value.toString && value.toString()); if (util.isNumber(value) /*&& (isNaN(value) || !isFinite(value))*/) { return value; } if (util.isFunction(value) || util.isRegExp(value)) { return value.toString(); } return value; }
drawBar: function(groupIndex, barIndex, callback) { var self = this, _cfg = self._cfg, paper = self.getRaphaelPaper(), ctn = self._innerContainer, color = self.color.getColor(groupIndex)['DEFAULT'], attr = self.processAttr(_cfg.bars.attr, color), isY = _cfg.zoomType == "x" ? false : true, barPos = self._barsPos[groupIndex][barIndex], x = Math.round(barPos.x - 0), y = Math.round(barPos.y - 0), w = Math.round(barPos.width - 0), h = Math.round(barPos.height - 0), rect; // 确保柱子有高度:数据为大于0的一个小数,产生的高度小于1。在y方向做一点修正 y-=2 if (h >= 0 && h <= 1) { h = 1; // y -= 2; } //允许动画 if (_cfg.anim) { var duration = _cfg.anim.duration ? (Util.isNumber(_cfg.anim.duration) ? _cfg.anim.duration : 500) : 500, easing = _cfg.anim.easing ? _cfg.anim.easing : "easeOut"; if (isY) { var zeroX = BaseChart.prototype.data2GrapicData.call(self, 0, true, false); rect = paper.rect(zeroX, y, 0, h).attr(attr).animate({ "width": w, "x": x }, duration, easing, function() { callback && callback(); }); } else { var zeroY = BaseChart.prototype.data2GrapicData.call(self, 0, false, true); rect = paper.rect(x, zeroY, w, 0).attr(attr).animate({ "height": h, "y": y }, duration, easing, function() { callback && callback(); }); } } else { rect = paper.rect(x, y, w, h).attr(attr); callback && callback(); } return rect; },
function(address, port, addressType, fd) { var err = 0; // assign handle in listen, and clean up if bind or listen fails var handle; if (util.isNumber(fd) && fd >= 0) { try { handle = createHandle(fd); } catch (e) { // Not a fd we can listen on. This will trigger an error. debug('listen invalid fd=' + fd + ': ' + e.message); return uv.UV_EINVAL; } handle.open(fd); handle.readable = true; handle.writable = true; return handle; } else if (port == -1 && addressType == -1) { handle = createPipe(); if (process.platform === 'win32') { var instances = parseInt(process.env.NODE_PENDING_PIPE_INSTANCES); if (!isNaN(instances)) { handle.setPendingInstances(instances); } } } else { handle = createTCP(); } if (address || port) { debug('bind to ' + address); if (addressType == 6) { err = handle.bind6(address, port); } else { err = handle.bind(address, port); } } if (err) { handle.close(); return err; } return handle; };
fs.truncateSync = function(path, len) { if (util.isNumber(path)) { // legacy return fs.ftruncateSync(path, len); } if (util.isUndefined(len)) { len = 0; } // allow error to be thrown, but still close fd. var fd = fs.openSync(path, 'r+'); try { var ret = fs.ftruncateSync(fd, len); } finally { fs.closeSync(fd); } return ret; };
/** * 扫描 paths 后返回 map * @private * @param {String[]} paths 路径数组 * @param {Object} config 配置 * @return {Promise} */ function Scanner (options) { var self = this var paths = options.paths var config = options.config console.log('there are %d paths', paths.length) console.log(paths) self.paths = paths self.config = config self.parser = options.parser // 依赖 map self.depMap = {} // 解析并发数 var threadNum = Default_Thread_Num if (util.isNumber(config.threadNum) && config.threadNum <= Max_Thread_Num) { threadNum = config.threadNum } console.log('threadNum %d', threadNum) // 每个并发数要解析的数量 var numPerThread = Math.floor(paths.length / threadNum) console.log('numPerThread %d', numPerThread) var promiseArray = [] // 任务分解 var remainder = paths.length - numPerThread * threadNum var counter = 1 while (counter <= threadNum) { var numToCut = numPerThread if (counter <= remainder) { numToCut = numPerThread + 1 } console.log('cutting %d', numToCut) promiseArray.push(self.scanThread(paths.splice(0, numToCut))) counter++ } Promise.all(promiseArray).then(function () { self.emit('end', self.depMap) return self.depMap }, function (error) { self.emit('error', error) }) }
Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { debug('listen2', address, port, addressType, backlog); var self = this; // If there is not yet a handle, we need to create one and bind. // In the case of a server sent via IPC, we don't need to do this. if (!self._handle) { debug('_listen2: create a handle'); var rval = createServerHandle(address, port, addressType, fd); if (util.isNumber(rval)) { var error = errnoException(rval, 'listen'); process.nextTick(function() { self.emit('error', error); }); return; } self._handle = rval; } else { debug('_listen2: have a handle already'); } self._handle.onconnection = onconnection; self._handle.owner = self; // Use a backlog of 512 entries. We pass 511 to the listen() call because // the kernel does: backlogsize = roundup_pow_of_two(backlogsize + 1); // which will thus give us a backlog of 512 entries. var err = self._handle.listen(backlog || 511); if (err) { var ex = errnoException(err, 'listen'); self._handle.close(); self._handle = null; process.nextTick(function() { self.emit('error', ex); }); return; } // generate connection key, this should be unique to the connection this._connectionKey = addressType + ':' + address + ':' + port; process.nextTick(function() { self.emit('listening'); }); };
// convert a js object to a string evaling to the same in cljs // flat=true to omit toplevel braces for argument application in templates function jsToClj (object, flat = false) { if (util.isString(object)) { if (object[0] === ':') { return object; // a keyword } if (object[0] === "'") { return object.slice(1); // a symbol } return JSON.stringify(object); } if (util.isNumber(object)) { return JSON.stringify(object); } if (util.isBoolean(object)) { return object ? "true" : "false"; } if (util.isUndefined(object)) { return ''; } if (util.isNull(object)) { return 'nil'; } if (util.isArray(object)) { const elements = object.map(jsToClj).join(' '); if (flat) { return elements; } return `[${elements}]`; } const pairs = Object.keys(object).map((k) => { return `${jsToClj(k)} ${jsToClj(object[k])}`; }).join(',\n'); if (flat) { return pairs; } return `{${pairs}}`; }
Readable.prototype.read = function(n) { var state = this._readableState; var res; if (!util.isNumber(n) || n > state.length) { n = state.length; } else if (n < 0) { n = 0; } if (n > 0) { res = readBuffer(this, n); } else { res = null; } return res; };
function SharedHandle(key, address, port, addressType, backlog, fd) { this.key = key; this.workers = []; this.handle = null; this.errno = 0; // FIXME(bnoordhuis) Polymorphic return type for lack of a better solution. var rval; if (addressType === 'udp4' || addressType === 'udp6') rval = dgram._createSocketHandle(address, port, addressType, fd); else rval = net._createServerHandle(address, port, addressType, fd); if (util.isNumber(rval)) this.errno = rval; else this.handle = rval; }
const timer = performance((data) => { assert(util.isNumber(data.lag)); const heapData = data.heap; const keys = Object.keys(heapData); keys.forEach((key) => { const v = heapData[key]; if (key === 'does_zap_garbage') { assert.equal(v, 0); return; } assert(util.isNumber(v)); if (key !== 'malloced_memory') { assert.notEqual(parseInt(v, 10), v); } }); done(); clearInterval(timer); }, '0.000GB', 10);
getById: function ( id ) { if ( !util.isNumber( id ) ) { throw new Error( 'id must be number' ); } var conn = getConn(); var sql = this.selectSql + 'where id=?'; var list = conn.execute( sql, id ); var post = null; if ( list && list.length ) { post = this.convertToPost( list[ 0 ] ); } return post; },
exports.lookup = function lookup(hostname, options, callback) { var hints = 0; var family = -1; // Parse arguments if (!util.isString(hostname)) { throw TypeError('invalid argument: hostname must be a string or falsey'); } if (util.isFunction(options)) { callback = options; family = 0; } else if (!util.isFunction(callback)) { throw TypeError('invalid argument: callback must be passed'); } else if (util.isObject(options)) { hints = options.hints >>> 0; family = options.family >>> 0; if (hints < 0 || hints > (exports.ADDRCONFIG | exports.V4MAPPED)) { throw new TypeError('invalid argument: invalid hints flags'); } } else if (util.isNumber(options)) { family = ~~options; } else { throw TypeError( 'invalid argument: options must be either an object or number'); } if (family !== 0 && family !== 4 && family !== 6) throw new TypeError('invalid argument: family must be 4 or 6'); var err = dnsBuiltin.getaddrinfo( hostname, family, hints, function(err, address, family) { var errObj = null; if (err) { errObj = dnsException(err, 'getaddrinfo', hostname); } return callback(errObj, address, family); }); return err; };
getByBlogId: function ( blogId ) { if ( !util.isNumber( blogId ) ) { throw new Error( 'wrong blog id' ); } var sql = this.selectSql + ' where blog_id=? ' + this.orderSql; var conn = getConn(); var dbList = conn.execute( sql, blogId ); var list = []; if ( dbList && dbList.length ) { dbList.forEach( function ( item, index ) { list[ index ] = this.convertToComment( item ); }.bind( this ) ); } return list; }
function normalizeListenArgs(args) { var options = {}; if (util.isObject(args[0])) { options = args[0]; } else { var idx = 0; options.port = args[idx++]; if (util.isString(args[idx])) { options.host = args[idx++]; } if (util.isNumber(args[idx])) { options.backlog = args[idx++]; } } var cb = args[args.length - 1]; return util.isFunction(cb) ? [options, cb] : [options]; }
post: function(id, e) { var userid = fib.userid(); userid = 1; // if (!getPower(userid, "blog")) return { // error: "noPower" // } var id = object.create(userid, "bbs", "", "message", e, []); if (!util.isNumber(id)) return { error: id }; var tb = dbapi[userid].blog; tb.put({ tag: "", bindid: id }); object.clearCache(userid, ["blog"]); return id; },
function PwmPin(configuration, callback) { var self = this; self._configuration = {}; if (util.isObject(configuration)) { if (process.platform === 'linux') { if (util.isNumber(configuration.chip)) { self._configuration.chip = configuration.chip } else { self._configuration.chip = 0; } } if (!util.isNumber(configuration.pin)) { throw new TypeError( 'Bad configuration - pin is mandatory and should be Number'); } else { self._configuration.pin = configuration.pin; } } else { throw new TypeError('Bad arguments - configuration should be Object') } // validate configuration var dutyCycle = configuration.dutyCycle; var period = configuration.period; if (!util.isNumber(period) && util.isNumber(configuration.frequency)) { period = 1.0 / configuration.frequency; } if (util.isNumber(dutyCycle) && dutyCycle >= 0.0 && dutyCycle <= 1.0 && util.isNumber(period) && util.isFinite(period) && period > 0) { self._configuration.dutyCycle = dutyCycle; self._configuration.period = period; } _binding = new pwm(self._configuration, function(err) { util.isFunction(callback) && callback.call(self, err); }); process.on('exit', (function(self) { return function() { if (_binding !== null) { self.closeSync(); } }; })(this)); }
fs.truncate = function(path, len, callback) { if (util.isNumber(path)) { // legacy return fs.ftruncate(path, len, callback); } if (util.isFunction(len)) { callback = len; len = 0; } else if (util.isUndefined(len)) { len = 0; } callback = maybeCallback(callback); fs.open(path, 'r+', function(er, fd) { if (er) return callback(er); binding.ftruncate(fd, len, function(er) { fs.close(fd, function(er2) { callback(er || er2); }); }); }); };
exports.enroll = function(item, msecs) { if (!util.isNumber(msecs)) { throw new TypeError('msecs must be a number'); } if (msecs < 0 || !isFinite(msecs)) { throw new RangeError('msecs must be a non-negative finite number'); } // if this item was already in a list somewhere // then we should unenroll it from that if (item._idleNext) unenroll(item); // Ensure that msecs fits into signed int32 if (msecs > TIMEOUT_MAX) { msecs = TIMEOUT_MAX; } item._idleTimeout = msecs; L.init(item); };
function Socket(options) { if (!(this instanceof Socket)) return new Socket(options); this._connecting = false; this._host = null; if (util.isNumber(options)) options = { fd: options }; // Legacy interface. else if (util.isUndefined(options)) options = {}; stream.Duplex.call(this, options); // these will be set once there is a connection this.readable = this.writable = false; // handle strings directly this._writableState.decodeStrings = false; // default to *not* allowing half open sockets this.allowHalfOpen = options && options.allowHalfOpen || false; }
WriteStream.prototype._write = function(data, encoding, cb) { if (!util.isBuffer(data)) return this.emit('error', new Error('Invalid data')); if (!util.isNumber(this.fd)) return this.once('open', function() { this._write(data, encoding, cb); }); var self = this; fs.write(this.fd, data, 0, data.length, this.pos, function(er, bytes) { if (er) { self.destroy(); return cb(er); } self.bytesWritten += bytes; cb(); }); if (!util.isUndefined(this.pos)) this.pos += data.length; };
function createConnection(port, host, options) { if (util.isObject(port)) { options = port; } else if (util.isObject(host)) { options = host; } else if (util.isObject(options)) { options = options; } else { options = {}; } if (util.isNumber(port)) { options.port = port; } if (util.isString(host)) { options.host = host; } debug('createConnection', options); return tls.connect(options); }
// usage: obj = alloc(n[, obj][, type]); function alloc(n, obj, type) { n = n >>> 0; if (util.isUndefined(obj)) obj = {}; if (util.isNumber(obj)) { type = obj >>> 0; obj = {}; } else if (util.isPrimitive(obj)) { throw new TypeError('obj must be an Object'); } // 1 == v8::kExternalByteArray, 9 == v8::kExternalPixelArray if (type < 1 || type > 9) throw new TypeError('unknown external array type: ' + type); if (util.isArray(obj)) throw new TypeError('Arrays are not supported'); if (n > kMaxLength) throw new RangeError('n > kMaxLength'); return smalloc.alloc(obj, n, type); }
fs.truncate = function(path, len, callback) { if (util.isNumber(path)) { return fs.ftruncate(path, len, callback); } if (util.isFunction(len)) { callback = len; len = 0; } else if (util.isUndefined(len)) { len = 0; } callback = maybeCallback(callback); fs.open(path, 'r+', function(er, fd) { if (er) return callback(er); var req = new FSReqWrap(); req.oncomplete = function ftruncateCb(er) { fs.close(fd, function(er2) { callback(er || er2); }); }; binding.ftruncate(fd, len, req); }); };