示例#1
0
CryptoStream.prototype._write = function write(data, encoding, cb) {
  assert(util.isNull(this._pending));

  // Black-hole data
  if (!this.pair.ssl) return cb(null);

  // When resuming session don't accept any new data.
  // And do not put too much data into openssl, before writing it from encrypted
  // side.
  //
  // TODO(indutny): Remove magic number, use watermark based limits
  if (!this._resumingSession &&
      this._opposite._internallyPendingBytes() < 128 * 1024) {
    // Write current buffer now
    var written;
    if (this === this.pair.cleartext) {
      debug('cleartext.write called with %d bytes', data.length);
      written = this.pair.ssl.clearIn(data, 0, data.length);
    } else {
      debug('encrypted.write called with %d bytes', data.length);
      written = this.pair.ssl.encIn(data, 0, data.length);
    }

    // Handle and report errors
    if (this.pair.ssl && this.pair.ssl.error) {
      return cb(this.pair.error(true));
    }

    // Force SSL_read call to cycle some states/data inside OpenSSL
    this.pair.cleartext.read(0);

    // Cycle encrypted data
    if (this.pair.encrypted._internallyPendingBytes())
      this.pair.encrypted.read(0);

    // Get NPN and Server name when ready
    this.pair.maybeInitFinished();

    // Whole buffer was written
    if (written === data.length) {
      if (this === this.pair.cleartext) {
        debug('cleartext.write succeed with ' + written + ' bytes');
      } else {
        debug('encrypted.write succeed with ' + written + ' bytes');
      }

      // Invoke callback only when all data read from opposite stream
      if (this._opposite._halfRead) {
        assert(util.isNull(this._sslOutCb));
        this._sslOutCb = cb;
      } else {
        cb(null);
      }
      return;
    } else if (written !== 0 && written !== -1) {
      assert(!this._retryAfterPartial);
      this._retryAfterPartial = true;
      this._write(data.slice(written), encoding, cb);
      this._retryAfterPartial = false;
      return;
    }
  } else {
    debug('cleartext.write queue is full');

    // Force SSL_read call to cycle some states/data inside OpenSSL
    this.pair.cleartext.read(0);
  }

  // No write has happened
  this._pending = data;
  this._pendingEncoding = encoding;
  this._pendingCallback = cb;

  if (this === this.pair.cleartext) {
    debug('cleartext.write queued with %d bytes', data.length);
  } else {
    debug('encrypted.write queued with %d bytes', data.length);
  }
};
示例#2
0
Readable.prototype.read = function(n) {
  debug('read', n);
  var state = this._readableState;
  var nOrig = n;

  if (!util.isNumber(n) || n > 0)
    state.emittedReadable = false;

  // if we're doing read(0) to trigger a readable event, but we
  // already have a bunch of data in the buffer, then just trigger
  // the 'readable' event and move on.
  if (n === 0 &&
      state.needReadable &&
      (state.length >= state.highWaterMark || state.ended)) {
    debug('read: emitReadable', state.length, state.ended);
    if (state.length === 0 && state.ended)
      endReadable(this);
    else
      emitReadable(this);
    return null;
  }

  n = howMuchToRead(n, state);

  // if we've ended, and we're now clear, then finish it up.
  if (n === 0 && state.ended) {
    if (state.length === 0)
      endReadable(this);
    return null;
  }

  // All the actual chunk generation logic needs to be
  // *below* the call to _read.  The reason is that in certain
  // synthetic stream cases, such as passthrough streams, _read
  // may be a completely synchronous operation which may change
  // the state of the read buffer, providing enough data when
  // before there was *not* enough.
  //
  // So, the steps are:
  // 1. Figure out what the state of things will be after we do
  // a read from the buffer.
  //
  // 2. If that resulting state will trigger a _read, then call _read.
  // Note that this may be asynchronous, or synchronous.  Yes, it is
  // deeply ugly to write APIs this way, but that still doesn't mean
  // that the Readable class should behave improperly, as streams are
  // designed to be sync/async agnostic.
  // Take note if the _read call is sync or async (ie, if the read call
  // has returned yet), so that we know whether or not it's safe to emit
  // 'readable' etc.
  //
  // 3. Actually pull the requested chunks out of the buffer and return.

  // if we need a readable event, then we need to do some reading.
  var doRead = state.needReadable;
  debug('need readable', doRead);

  // if we currently have less than the highWaterMark, then also read some
  if (state.length === 0 || state.length - n < state.highWaterMark) {
    doRead = true;
    debug('length less than watermark', doRead);
  }

  // however, if we've ended, then there's no point, and if we're already
  // reading, then it's unnecessary.
  if (state.ended || state.reading) {
    doRead = false;
    debug('reading or ended', doRead);
  }

  if (doRead) {
    debug('do read');
    state.reading = true;
    state.sync = true;
    // if the length is currently zero, then we *need* a readable event.
    if (state.length === 0)
      state.needReadable = true;
    // call internal read method
    this._read(state.highWaterMark);
    state.sync = false;
  }

  // If _read pushed data synchronously, then `reading` will be false,
  // and we need to re-evaluate how much data we can return to the user.
  if (doRead && !state.reading)
    n = howMuchToRead(nOrig, state);

  var ret;
  if (n > 0)
    ret = fromList(n, state);
  else
    ret = null;

  if (util.isNull(ret)) {
    state.needReadable = true;
    n = 0;
  }

  state.length -= n;

  // If we have nothing in the buffer, then we want to know
  // as soon as we *do* get something into the buffer.
  if (state.length === 0 && !state.ended)
    state.needReadable = true;

  // If we tried to read() past the EOF, then emit end on the next tick.
  if (nOrig !== n && state.ended && state.length === 0)
    endReadable(this);

  if (!util.isNull(ret))
    this.emit('data', ret);

  return ret;
};
示例#3
0
fs.realpathSync = function realpathSync(p, cache) {
  // make p is absolute
  p = pathModule.resolve(p);

  if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
    return cache[p];
  }

  var original = p,
      seenLinks = {},
      knownHard = {};

  // current character position in p
  var pos;
  // the partial path so far, including a trailing slash if any
  var current;
  // the partial path without a trailing slash (except when pointing at a root)
  var base;
  // the partial path scanned in the previous round, with slash
  var previous;

  start();

  function start() {
    // Skip over roots
    var m = splitRootRe.exec(p);
    pos = m[0].length;
    current = m[0];
    base = m[0];
    previous = '';

    // On windows, check that the root exists. On unix there is no need.
    if (isWindows && !knownHard[base]) {
      fs.lstatSync(base);
      knownHard[base] = true;
    }
  }

  // walk down the path, swapping out linked pathparts for their real
  // values
  // NB: p.length changes.
  while (pos < p.length) {
    // find the next part
    nextPartRe.lastIndex = pos;
    var result = nextPartRe.exec(p);
    previous = current;
    current += result[0];
    base = previous + result[1];
    pos = nextPartRe.lastIndex;

    // continue if not a symlink
    if (knownHard[base] || (cache && cache[base] === base)) {
      continue;
    }

    var resolvedLink;
    if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
      // some known symbolic link.  no need to stat again.
      resolvedLink = cache[base];
    } else {
      var stat = fs.lstatSync(base);
      if (!stat.isSymbolicLink()) {
        knownHard[base] = true;
        if (cache) cache[base] = base;
        continue;
      }

      // read the link if it wasn't read before
      // dev/ino always return 0 on windows, so skip the check.
      var linkTarget = null;
      if (!isWindows) {
        var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
        if (seenLinks.hasOwnProperty(id)) {
          linkTarget = seenLinks[id];
        }
      }
      if (util.isNull(linkTarget)) {
        fs.statSync(base);
        linkTarget = fs.readlinkSync(base);
      }
      resolvedLink = pathModule.resolve(previous, linkTarget);
      // track this, if given a cache.
      if (cache) cache[base] = resolvedLink;
      if (!isWindows) seenLinks[id] = linkTarget;
    }

    // resolve the link, then start over
    p = pathModule.resolve(resolvedLink, p.slice(pos));
    start();
  }

  if (cache) cache[original] = p;

  return p;
};
示例#4
0
	it('isNull', function() {
		assert.isTrue(util.isNull(null));
		assert.isFalse(util.isNull(undefined));
		assert.isFalse(util.isNull(100));
	});
示例#5
0
文件: test-util.js 项目: bammons/node
// _extend
assert.deepStrictEqual(util._extend({a: 1}), {a: 1});
assert.deepStrictEqual(util._extend({a: 1}, []), {a: 1});
assert.deepStrictEqual(util._extend({a: 1}, null), {a: 1});
assert.deepStrictEqual(util._extend({a: 1}, true), {a: 1});
assert.deepStrictEqual(util._extend({a: 1}, false), {a: 1});
assert.deepStrictEqual(util._extend({a: 1}, {b: 2}), {a: 1, b: 2});
assert.deepStrictEqual(util._extend({a: 1, b: 2}, {b: 3}), {a: 1, b: 3});

// deprecated
assert.strictEqual(util.isBoolean(true), true);
assert.strictEqual(util.isBoolean(false), true);
assert.strictEqual(util.isBoolean('string'), false);

assert.strictEqual(util.isNull(null), true);
assert.strictEqual(util.isNull(), false);
assert.strictEqual(util.isNull('string'), false);

assert.strictEqual(util.isUndefined(), true);
assert.strictEqual(util.isUndefined(null), false);
assert.strictEqual(util.isUndefined('string'), false);

assert.strictEqual(util.isNullOrUndefined(null), true);
assert.strictEqual(util.isNullOrUndefined(), true);
assert.strictEqual(util.isNullOrUndefined('string'), false);

assert.strictEqual(util.isNumber(42), true);
assert.strictEqual(util.isNumber(), false);
assert.strictEqual(util.isNumber('string'), false);
示例#6
0
文件: Utils.js 项目: JanChou/Cube
base.isUndefinedorNull = function (v) {
    return base.isNull(v) || base.isUndefined(v);
}
示例#7
0
文件: _tls_wrap.js 项目: AtomLaw/node
 this.server._contexts.some(function(elem) {
   if (!util.isNull(servername.match(elem[0]))) {
     ctx = elem[1];
     return true;
   }
 });
示例#8
0
CryptoStream.prototype._read = function read(size) {
  // XXX: EOF?!
  if (!this.pair.ssl) return this.push(null);

  // Wait for session to be resumed
  // Mark that we're done reading, but don't provide data or EOF
  if (this._resumingSession || !this._reading) return this.push('');

  var out;
  if (this === this.pair.cleartext) {
    debug('cleartext.read called with %d bytes', size);
    out = this.pair.ssl.clearOut;
  } else {
    debug('encrypted.read called with %d bytes', size);
    out = this.pair.ssl.encOut;
  }

  var bytesRead = 0,
      start = this._buffer.offset;
  do {
    var read = this._buffer.use(this.pair.ssl, out, size - bytesRead);
    if (read > 0) {
      bytesRead += read;
    }

    // Handle and report errors
    if (this.pair.ssl && this.pair.ssl.error) {
      this.pair.error();
      break;
    }

    // Get NPN and Server name when ready
    this.pair.maybeInitFinished();

    // `maybeInitFinished()` can emit the 'secure' event which
    // in turn destroys the connection in case of authentication
    // failure and sets `this.pair.ssl` to `null`.
  } while (read > 0 &&
           !this._buffer.isFull &&
           bytesRead < size &&
           this.pair.ssl !== null);

  // Create new buffer if previous was filled up
  var pool = this._buffer.pool;
  if (this._buffer.isFull) this._buffer.create();

  assert(bytesRead >= 0);

  if (this === this.pair.cleartext) {
    debug('cleartext.read succeed with %d bytes', bytesRead);
  } else {
    debug('encrypted.read succeed with %d bytes', bytesRead);
  }

  // Try writing pending data
  if (!util.isNull(this._pending)) this._writePending();
  if (!util.isNull(this._opposite._pending)) this._opposite._writePending();

  if (bytesRead === 0) {
    // EOF when cleartext has finished and we have nothing to read
    if (this._opposite._finished && this._internallyPendingBytes() === 0) {
      // Perform graceful shutdown
      this._done();

      // No half-open, sorry!
      if (this === this.pair.cleartext)
        this._opposite._done();

      // EOF
      this.push(null);
    } else {
      // Bail out
      this.push('');
    }
  } else {
    // Give them requested data
    this.push(pool.slice(start, start + bytesRead));
  }

  // Let users know that we've some internal data to read
  var halfRead = this._internallyPendingBytes() !== 0;

  // Smart check to avoid invoking 'sslOutEnd' in the most of the cases
  if (this._halfRead !== halfRead) {
    this._halfRead = halfRead;

    // Notify listeners about internal data end
    if (!halfRead) {
      if (this === this.pair.cleartext) {
        debug('cleartext.sslOutEnd');
      } else {
        debug('encrypted.sslOutEnd');
      }

      this.emit('sslOutEnd');
    }
  }
};
示例#9
0
Url.prototype.resolveObject = function(relative) {
    if (util.isString(relative)) {
        var rel = new Url();
        rel.parse(relative, false, true);
        relative = rel;
    }

    var result = new Url();
    Object.keys(this).forEach(function(k) {
        result[k] = this[k];
    }, this);

    // hash is always overridden, no matter what.
    // even href="" will remove it.
    result.hash = relative.hash;

    // if the relative url is empty, then there's nothing left to do here.
    if (relative.href === '') {
        result.href = result.format();
        return result;
    }

    // hrefs like //foo/bar always cut to the protocol.
    if (relative.slashes && !relative.protocol) {
        // take everything except the protocol from relative
        Object.keys(relative).forEach(function(k) {
            if (k !== 'protocol')
                result[k] = relative[k];
        });

        //urlParse appends trailing / to urls like http://www.example.com
        if (slashedProtocol[result.protocol] &&
            result.hostname && !result.pathname) {
            result.path = result.pathname = '/';
        }

        result.href = result.format();
        return result;
    }

    if (relative.protocol && relative.protocol !== result.protocol) {
        // if it's a known url protocol, then changing
        // the protocol does weird things
        // first, if it's not file:, then we MUST have a host,
        // and if there was a path
        // to begin with, then we MUST have a path.
        // if it is file:, then the host is dropped,
        // because that's known to be hostless.
        // anything else is assumed to be absolute.
        if (!slashedProtocol[relative.protocol]) {
            Object.keys(relative).forEach(function(k) {
                result[k] = relative[k];
            });
            result.href = result.format();
            return result;
        }

        result.protocol = relative.protocol;
        if (!relative.host && !hostlessProtocol[relative.protocol]) {
            var relPath = (relative.pathname || '').split('/');
            while (relPath.length && !(relative.host = relPath.shift()));
            if (!relative.host) relative.host = '';
            if (!relative.hostname) relative.hostname = '';
            if (relPath[0] !== '') relPath.unshift('');
            if (relPath.length < 2) relPath.unshift('');
            result.pathname = relPath.join('/');
        } else {
            result.pathname = relative.pathname;
        }
        result.search = relative.search;
        result.query = relative.query;
        result.host = relative.host || '';
        result.auth = relative.auth;
        result.hostname = relative.hostname || relative.host;
        result.port = relative.port;
        // to support http.request
        if (result.pathname || result.search) {
            var p = result.pathname || '';
            var s = result.search || '';
            result.path = p + s;
        }
        result.slashes = result.slashes || relative.slashes;
        result.href = result.format();
        return result;
    }

    var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
        isRelAbs = (
            relative.host ||
            relative.pathname && relative.pathname.charAt(0) === '/'
        ),
        mustEndAbs = (isRelAbs || isSourceAbs ||
            (result.host && relative.pathname)),
        removeAllDots = mustEndAbs,
        srcPath = result.pathname && result.pathname.split('/') || [],
        relPath = relative.pathname && relative.pathname.split('/') || [],
        psychotic = result.protocol && !slashedProtocol[result.protocol];

    // if the url is a non-slashed url, then relative
    // links like ../.. should be able
    // to crawl up to the hostname, as well.  This is strange.
    // result.protocol has already been set by now.
    // Later on, put the first path part into the host field.
    if (psychotic) {
        result.hostname = '';
        result.port = null;
        if (result.host) {
            if (srcPath[0] === '') srcPath[0] = result.host;
            else srcPath.unshift(result.host);
        }
        result.host = '';
        if (relative.protocol) {
            relative.hostname = null;
            relative.port = null;
            if (relative.host) {
                if (relPath[0] === '') relPath[0] = relative.host;
                else relPath.unshift(relative.host);
            }
            relative.host = null;
        }
        mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
    }

    if (isRelAbs) {
        // it's absolute.
        result.host = (relative.host || relative.host === '') ?
            relative.host : result.host;
        result.hostname = (relative.hostname || relative.hostname === '') ?
            relative.hostname : result.hostname;
        result.search = relative.search;
        result.query = relative.query;
        srcPath = relPath;
        // fall through to the dot-handling below.
    } else if (relPath.length) {
        // it's relative
        // throw away the existing file, and take the new path instead.
        if (!srcPath) srcPath = [];
        srcPath.pop();
        srcPath = srcPath.concat(relPath);
        result.search = relative.search;
        result.query = relative.query;
    } else if (!util.isNullOrUndefined(relative.search)) {
        // just pull out the search.
        // like href='?foo'.
        // Put this after the other two cases because it simplifies the booleans
        if (psychotic) {
            result.hostname = result.host = srcPath.shift();
            //occationaly the auth can get stuck only in host
            //this especialy happens in cases like
            //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
            var authInHost = result.host && result.host.indexOf('@') > 0 ?
                result.host.split('@') : false;
            if (authInHost) {
                result.auth = authInHost.shift();
                result.host = result.hostname = authInHost.shift();
            }
        }
        result.search = relative.search;
        result.query = relative.query;
        //to support http.request
        if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
            result.path = (result.pathname ? result.pathname : '') +
                (result.search ? result.search : '');
        }
        result.href = result.format();
        return result;
    }

    if (!srcPath.length) {
        // no path at all.  easy.
        // we've already handled the other stuff above.
        result.pathname = null;
        //to support http.request
        if (result.search) {
            result.path = '/' + result.search;
        } else {
            result.path = null;
        }
        result.href = result.format();
        return result;
    }

    // if a url ENDs in . or .., then it must get a trailing slash.
    // however, if it ends in anything else non-slashy,
    // then it must NOT get a trailing slash.
    var last = srcPath.slice(-1)[0];
    var hasTrailingSlash = (
        (result.host || relative.host) && (last === '.' || last === '..') ||
        last === '');

    // strip single dots, resolve double dots to parent dir
    // if the path tries to go above the root, `up` ends up > 0
    var up = 0;
    for (var i = srcPath.length; i >= 0; i--) {
        last = srcPath[i];
        if (last == '.') {
            srcPath.splice(i, 1);
        } else if (last === '..') {
            srcPath.splice(i, 1);
            up++;
        } else if (up) {
            srcPath.splice(i, 1);
            up--;
        }
    }

    // if the path is allowed to go above the root, restore leading ..s
    if (!mustEndAbs && !removeAllDots) {
        for (; up--; up) {
            srcPath.unshift('..');
        }
    }

    if (mustEndAbs && srcPath[0] !== '' &&
        (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
        srcPath.unshift('');
    }

    if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
        srcPath.push('');
    }

    var isAbsolute = srcPath[0] === '' ||
        (srcPath[0] && srcPath[0].charAt(0) === '/');

    // put the host back
    if (psychotic) {
        result.hostname = result.host = isAbsolute ? '' :
            srcPath.length ? srcPath.shift() : '';
        //occationaly the auth can get stuck only in host
        //this especialy happens in cases like
        //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
        var authInHost = result.host && result.host.indexOf('@') > 0 ?
            result.host.split('@') : false;
        if (authInHost) {
            result.auth = authInHost.shift();
            result.host = result.hostname = authInHost.shift();
        }
    }

    mustEndAbs = mustEndAbs || (result.host && srcPath.length);

    if (mustEndAbs && !isAbsolute) {
        srcPath.unshift('');
    }

    if (!srcPath.length) {
        result.pathname = null;
        result.path = null;
    } else {
        result.pathname = srcPath.join('/');
    }

    //to support request.http
    if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
        result.path = (result.pathname ? result.pathname : '') +
            (result.search ? result.search : '');
    }
    result.auth = relative.auth || result.auth;
    result.slashes = result.slashes || relative.slashes;
    result.href = result.format();
    return result;
};
示例#10
0
 stopfile: (x) => nutil.isNull(x) || nutil.isRegExp(x) || utils.all(x, nutil.isRegExp),
示例#11
0
 modules: (x) => nutil.isNull(x) || utils.all(x, nutil.isString),
示例#12
0
 exclude: (x) => nutil.isNull(x) || nutil.isRegExp(x) || utils.all(x, nutil.isRegExp),
示例#13
0
 it('isNull', () => {
     assert.isTrue(util.isNull(null));
     assert.isFalse(util.isNull(undefined));
     assert.isFalse(util.isNull(100));
 });
示例#14
0
function hasOwnProperty(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function charCode(e){return e.charCodeAt(0)}var QueryString=exports,util=require("util");QueryString.unescapeBuffer=function(e,t){var n=new Buffer(e.length),r="CHAR",i,s,o;for(var u=0,a=0;u<=e.length;u++){var f=e.charCodeAt(u);switch(r){case"CHAR":switch(f){case charCode("%"):i=0,s=0,r="HEX0";break;case charCode("+"):t&&(f=charCode(" "));default:n[a++]=f}break;case"HEX0":r="HEX1",o=f;if(charCode("0")<=f&&f<=charCode("9"))i=f-charCode("0");else if(charCode("a")<=f&&f<=charCode("f"))i=f-charCode("a")+10;else{if(!(charCode("A")<=f&&f<=charCode("F"))){n[a++]=charCode("%"),n[a++]=f,r="CHAR";break}i=f-charCode("A")+10}break;case"HEX1":r="CHAR";if(charCode("0")<=f&&f<=charCode("9"))s=f-charCode("0");else if(charCode("a")<=f&&f<=charCode("f"))s=f-charCode("a")+10;else{if(!(charCode("A")<=f&&f<=charCode("F"))){n[a++]=charCode("%"),n[a++]=o,n[a++]=f;break}s=f-charCode("A")+10}n[a++]=16*i+s}}return n.slice(0,a-1)},QueryString.unescape=function(e,t){return QueryString.unescapeBuffer(e,t).toString()},QueryString.escape=function(e){return encodeURIComponent(e)};var stringifyPrimitive=function(e){return util.isString(e)?e:util.isBoolean(e)?e?"true":"false":util.isNumber(e)?isFinite(e)?e:"":""};QueryString.stringify=QueryString.encode=function(e,t,n,r){return t=t||"&",n=n||"=",util.isNull(e)&&(e=undefined),util.isObject(e)?Object.keys(e).map(function(r){var i=QueryString.escape(stringifyPrimitive(r))+n;return util.isArray(e[r])?e[r].map(function(e){return i+QueryString.escape(stringifyPrimitive(e))}).join(t):i+QueryString.escape(stringifyPrimitive(e[r]))}).join(t):r?QueryString.escape(stringifyPrimitive(r))+n+QueryString.escape(stringifyPrimitive(e)):""},QueryString.parse=QueryString.decode=function(e,t,n,r){t=t||"&",n=n||"=";var i={};if(!util.isString(e)||e.length===0)return i;var s=/\+/g;e=e.split(t);var o=1e3;r&&util.isNumber(r.maxKeys)&&(o=r.maxKeys);var u=e.length;o>0&&u>o&&(u=o);for(var a=0;a<u;++a){var f=e[a].replace(s,"%20"),l=f.indexOf(n),c,h,p,d;l>=0?(c=f.substr(0,l),h=f.substr(l+1)):(c=f,h="");try{p=decodeURIComponent(c),d=decodeURIComponent(h)}catch(v){p=QueryString.unescape(c,!0),d=QueryString.unescape(h,!0)}hasOwnProperty(i,p)?util.isArray(i[p])?i[p].push(d):i[p]=[i[p],d]:i[p]=d}return i}
示例#15
0
文件: zlib.js 项目: 4ntoine/Nodelike
Zlib.prototype._transform = function(chunk, encoding, cb) {
  var flushFlag;
  var ws = this._writableState;
  var ending = ws.ending || ws.ended;
  var last = ending && (!chunk || ws.length === chunk.length);

  if (!util.isNull(chunk) && !util.isBuffer(chunk))
    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 explicitly flushing at some other time, then we use
  // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
  // goodness.
  if (last)
    flushFlag = binding.Z_FINISH;
  else {
    flushFlag = this._flushFlag;
    // once we've flushed the last of the queue, stop flushing and
    // go back to the normal behavior.
    if (chunk.length >= ws.length) {
      this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
    }
  }

  var availInBefore = chunk && chunk.length;
  var availOutBefore = this._chunkSize - this._offset;
  var inOff = 0;

  var req = this._binding.write(flushFlag,
                                chunk, // in
                                inOff, // in_off
                                availInBefore, // in_len
                                this._buffer, // out
                                this._offset, //out_off
                                availOutBefore); // out_len

  req.buffer = chunk;
  req.callback = callback;

  var self = this;
  function callback(availInAfter, availOutAfter) {
    if (self._hadError)
      return;

    var have = availOutBefore - availOutAfter;
    assert(have >= 0, 'have should not go down');

    if (have > 0) {
      var out = self._buffer.slice(self._offset, self._offset + have);
      self._offset += have;
      // serve some output to the consumer.
      self.push(out);
    }

    // exhausted the output buffer, or used all the input create a new one.
    if (availOutAfter === 0 || self._offset >= self._chunkSize) {
      availOutBefore = self._chunkSize;
      self._offset = 0;
      self._buffer = new Buffer(self._chunkSize);
    }

    if (availOutAfter === 0) {
      // Not actually done.  Need to reprocess.
      // Also, update the availInBefore to the availInAfter value,
      // so that if we have to hit it a third (fourth, etc.) time,
      // it'll have the correct byte counts.
      inOff += (availInBefore - availInAfter);
      availInBefore = availInAfter;

      var newReq = self._binding.write(flushFlag,
                                       chunk,
                                       inOff,
                                       availInBefore,
                                       self._buffer,
                                       self._offset,
                                       self._chunkSize);
      newReq.callback = callback; // this same function
      newReq.buffer = chunk;
      return;
    }

    // finished with the chunk.
    cb();
  }
};
示例#16
0
exports.updateOrganResource = function (req,res) {
    // 从cache中更新组织数据
    var _userName = req.session.user.name;
    var _userId = req.session.user._id.toString();
    var _organNameHashMap = Cache.get(_userName);
    if ( Util.isNull(_organNameHashMap) ) {
        res.redirect('/organ/organList');
    }
    var _empList = _organNameHashMap.get('Employee')!=null?_organNameHashMap.get('Employee').toArray():null; // 获取员工更新信息;
    var _roleList = _organNameHashMap.get('Role')!=null? _organNameHashMap.get('Role').toArray():null;  // 获取角色更新信息
    var _depList =  _organNameHashMap.get('Department')!=null?_organNameHashMap.get('Department').toArray():null;  // 获取部门更新信息
    var _posList =  _organNameHashMap.get('Position')!=null?_organNameHashMap.get('Position').toArray():null;  // 获取职位更新信息
    var empPromise = new Promise(function(resolve,reject){
        executeEmpOpe(_userId,_empList,function(empRes){
            if ( empRes) {
                resolve("success");
            }else {
                reject("failed");
            }
        });
    });
    var rolePromise;  // 角色Promise
    var depPromise;   // 部门promise
    var posPromise;   // 职位promise
    var updateRoles;  // 更新的组织角色信息
    var updateDeps;   // 更新的组织部门信息
    var updatePos;   // 更新的组织职位信息
    Organ.findOne({userId:_userId},function(error,organ){
        if ( error  ) {
            err(error,"组织信息查找失败"+_userId);
        }
        if ( organ == null || organ.length ==0  ) {
            err(null,"请admin先添加组织信息");
        }
        rolePromise = new Promise(function(resolve,reject){
             executeRoleOpe(_roleList,organ.organName,_userId,function(_updateRoles,roleRes){
                 if ( roleRes ) {   // 更新角色信息
                     updateRoles = _updateRoles;
                     resolve("success");
                 } else {
                     reject("failed");
                 }
            });
        });
        depPromise = new Promise(function(resolve,reject){
             executeDepOpe(_depList,organ.organName,_userId, function (_updateDeps, depRes) {
                if(depRes) {  // 更新部门信息
                     updateDeps = _updateDeps;
                     resolve("success");
                 }else {
                     reject("failed");
                 }
             });
        });
        posPromise = new Promise( function (resolve,reject) {
            executePosOpe(_posList,organ.organName,_userId,function(_updatePos, posRes) {
                if (posRes) {   //  更新职位信息
                    updatePos = _updatePos;
                    resolve("success");
                } else {
                    reject("failed");
                }
            });
        });
        // 当empPromise、rolePromise、depPromise、posPromise都完成的时候,或者有一个发生异常时: resData:为一个各个Promise返回结果集
        Promise.all([empPromise,rolePromise,depPromise,posPromise]).then(function( resData ){
            server.listen(80);
            io.sockets.on('connection', function (socket) {
                console.log("socket connected:"+socket.id);
                //// 对分组中的用户发送信息 (包括自己)
             //   io.sockets.in('roles').emit('roles'+_userId, { updateRole: updateRoles }); // 发送角色更新信息

                socket.emit('roles'+_userId, { updateRole: updateRoles },function(data){  // 发送角色更新信息
                    if ( data == 200) {
                      //  updateRoles = null;
                        console.log("客户端接收角色更新信息成功!");
                    }
                });
                socket.emit('departments'+_userId, { updateDep: updateDeps },function(data){
                    if ( data == 200) {
                     //   updateDeps = null;
                        console.log("客户端接收部门更新信息成功!");
                    }
                });
                socket.emit('positions'+_userId, { updatePos: updatePos },function(data){
                    if ( data == 200) {
                      //  updatePos = null;
                        console.log("客户端接收职位更新信息成功!");
                    }
                });
               // io.socket.on(_userId,function(data){
               //     console.log("新加入"+data);
               //     socket.join(_userId);   //  以管理员分组,每个管理员和其添加的协作人为一组
               // });
               // socket.broadcast.to(_userId).emit('roles'+_userId,{updateRole:updateRoles}); // 对分组中的用户发信息
            });
            io.sockets.on('disconnection',function(socket){

            });
            Cache.del(_userName); // 从缓存中删除已经执行的数据
            console.log("updateOrganResource");
            res.redirect('/organ/organList');
        })

    });

};