Note: we could use the traditional "response"/"data"/"end" events too if we wanted to stream data incrementally, limit download size, etc. - but the simple callback is good enough for our needs.
972635
function (error, response, body) {
            if (error) {
                // Usually means we never got a response - server is down, no DNS entry, etc.
                _endDownload(downloadId, Errors.NO_SERVER_RESPONSE);
                return;
            }
            if (response.statusCode !== 200) {
                _endDownload(downloadId, [Errors.BAD_HTTP_STATUS, response.statusCode]);
                return;
            }

            var stream = temp.createWriteStream("brackets");
            if (!stream) {
                _endDownload(downloadId, Errors.CANNOT_WRITE_TEMP);
                return;
            }
            pendingDownloads[downloadId].localPath = stream.path;
            pendingDownloads[downloadId].outStream = stream;

            stream.write(body);
            _endDownload(downloadId);
        }
429373
function(err, chunk)
  {
    // unsubscribe from the 'loadcomplete' event
    chunk.removeListener('loadcomplete', onLoadComplete);

    // if the chunk load succeeded
    if (!err)
    {
      // move on to the next chunk
      start++;

      // emit an event to signal that new data is available
      self.emit('data', chunk);
    }
    else
    {
      // close the stream with an error; also, include a callback when emitting
      // the event in case someone wants to fix the problem and ask us to
      // continue from where we got interrupted
      close(self, err, doLoad);
    }
  }
253081
function respond () {
  let res = this.res
  let body = this.body
  let code = this.status

  if (this.respond === false) return endContext(this)
  if (res.headersSent || this._finished != null) return

  this.set('server', 'Toa/' + Toa.VERSION)
  if (this.config.poweredBy) this.set('x-powered-by', this.config.poweredBy)
  // ignore body
  if (statuses.empty[code]) {
    // strip headers
    this.body = null
    res.end()
  } else if (this.method === 'HEAD') {
    if (isJSON(body)) this.length = Buffer.byteLength(JSON.stringify(body))
    res.end()
  } else if (body == null) {
    // status body
    this.type = 'text'
    body = this.message || String(code)
    this.length = Buffer.byteLength(body)
    res.end(body)
  } else if (typeof body === 'string' || Buffer.isBuffer(body)) {
    res.end(body)
  } else if (body instanceof Stream) {
    body.pipe(res)
    // to ensure `res.headersSent === true` before `context.emit("end")`
    // if "error" occured before "data", it will goto `onResError(this, error)`
    body.once('data', () => endContext(this))
    return
  } else {
    // body: json
    body = JSON.stringify(body)
    this.length = Buffer.byteLength(body)
    res.end(body)
  }
  endContext(this)
}
1056538
def post_process(self, stream_to_file=False):
        
        self.status_code = self.response.status_code
        if 200 <= self.status_code < 300:
            if stream_to_file:
                self.stream_to_file(stream_to_file)
            else:
                self.extract_data()
        else:
            self._timestamps.setdefault('exception', time.time())
            if self.status_code in HTTP_STATUS_CODES:
                self.error = HTTP_STATUS_CODES[self.status_code].str_to_obj(
                    self.response.content)
            else:
                self.error = Exception('Status code = %s' % self.status_code)
            raise self.error
697038
function forceEnd(path, response) {

            // Send a custom response for gateway timeout
            new $CustomResponse().head(504, null, {
                'Content-Type': 'text/html'
            }).writeSync(`<h1>${RESPONSE_HEADER_MESSAGES[ 504 ]}</h1>`);

            // Log something
            $LogProvider.error(path, response._header);

            // End the response
            end(response);
        }
482992
def __SendMediaRequest(self, request, end):
        """"""
        def CheckResponse(response):
            if response is None:
                # Caller shouldn't call us if the response is None,
                # but handle anyway.
                raise exceptions.RequestError(
                    'Request to url %s did not return a response.' %
                    response.request_url)
        response = http_wrapper.MakeRequest(
            self.bytes_http, request, retry_func=self.retry_func,
            retries=self.num_retries, check_response_func=CheckResponse)
        if response.status_code == http_wrapper.RESUME_INCOMPLETE:
            last_byte = self.__GetLastByte(
                self._GetRangeHeaderFromResponse(response))
            if last_byte + 1 != end:
                self.stream.seek(last_byte + 1)
        return response
1058129
function streamOutput( callback ) {
	return function(err, filenames) {
		if (err) {
			callback(err, null);
		} else {
			// Create read streams from each input
			var streams = []
			for (var i=0; i<filenames.suffix.length; i++)
				streams.push([
					fs.createReadStream( filenames.basename + filenames.suffix[i]),
					filenames.suffix[i]
				]);
			// Callback with streams
			callback(err, streams);
		}
	}
}
888733
function onRequest(request, response) {
  var filename = path.join(__dirname, request.url);

  // Serving server.js from cache. Useful for microbenchmarks.
  if (request.url === cachedUrl) {
    if (response.push) {
      // Also push down the client js, since it's possible if the requester wants
      // one, they want both.
      var push = response.push('/client.js');
      push.writeHead(200);
      fs.createReadStream(path.join(__dirname, '/client.js')).pipe(push);
    }
    response.end(cachedFile);
  }

  // Reading file from disk if it exists and is safe.
  else if ((filename.indexOf(__dirname) === 0) && fs.existsSync(filename) && fs.statSync(filename).isFile()) {
    response.writeHead(200);
    var fileStream = fs.createReadStream(filename);
    fileStream.pipe(response);
    fileStream.on('finish',response.end);
  }

  // Example for testing large (boundary-sized) frames.
  else if (request.url === "/largeframe") {
    response.writeHead(200);
    var body = 'a';
    for (var i = 0; i < 14; i++) {
      body += body;
    }
    body = body + 'a';
    response.end(body);
  }

  // Otherwise responding with 404.
  else {
    response.writeHead(404);
    response.end();
  }
}
150149
function ReadableUSBStream(endpoint, options)
{
	stream.Readable.call(this, options);

	this.endpoint = endpoint;
	this.endpoint.addListener('data', this.onData.bind(this));
	this.endpoint.addListener('error', this.onError.bind(this));
	this.endpoint.addListener('end', this.onEnd.bind(this));

	this.paused = true;
}
264705
def _process_file_continue_response(self, response: HTTPResponse):
        ''''''
        code = response.status_code

        if code == http.client.PARTIAL_CONTENT:
            self.open_file(self._filename, response, mode='ab+')
        else:
            self._raise_cannot_continue_error()
1345914
def stream_upload(self, data, callback):
        
        while True:
            chunk = data.read(self.config.connection.data_block_size)
            if not chunk:
                break
            if callback and callable(callback):
                callback(chunk, response=None)
            yield chunk
146808
async function close(callback) {
            await closeStream(client.stream);
            await closeStream(client.rpc);
            if (callback) {
                return callback();
            }
        }
7460
function download(source, { verbose, output, onStart, onProgress } = {}) {
  return new Promise(function(y, n) {
    if (typeof output === 'undefined') {
      output = path.basename(url.parse(source).pathname) || 'unknown';
    }

    /**
     * Parse the source url into parts
     */
    const sourceUrl = url.parse(source);

    /**
     * Determine to use https or http request depends on source url
     */
    let request = null;
    if (sourceUrl.protocol === 'https:') {
      request = https.request;
    } else if (sourceUrl.protocol === 'http:') {
      request = http.request;
    } else {
      throw new Error('protocol should be http or https');
    }

    /**
     * Issue the request
     */
    const req = request(
      {
        method: 'GET',
        protocol: sourceUrl.protocol,
        host: sourceUrl.hostname,
        port: sourceUrl.port,
        path: sourceUrl.pathname + (sourceUrl.search || '')
      },
      function(res) {
        if (res.statusCode === 200) {
          const fileSize = Number.isInteger(res.headers['content-length'] - 0)
            ? parseInt(res.headers['content-length'])
            : 0;
          let downloadedSize = 0;

          /**
           * Create write stream
           */
          var writeStream = fs.createWriteStream(output, {
            flags: 'w+',
            encoding: 'binary'
          });

          res.pipe(writeStream);

          /**
           * Invoke `onStartCallback` function
           */
          if (onStart) {
            onStart(res.headers);
          }

          res.on('data', function(chunk) {
            downloadedSize += chunk.length;
            if (onProgress) {
              onProgress({
                fileSize,
                downloadedSize,
                percentage: fileSize > 0 ? downloadedSize / fileSize : 0
              });
            }
          });

          res.on('error', function(err) {
            writeStream.end();
            n(err);
          });

          writeStream.on('finish', function() {
            writeStream.end();
            req.end('finished');
            y({ headers: res.headers, fileSize });
          });
        } else if (
          res.statusCode === 301 ||
          res.statusCode === 302 ||
          res.statusCode === 307
        ) {
          const redirectLocation = res.headers.location;

          if (verbose) {
            console.log('node-wget-promise: Redirected to:', redirectLocation);
          }

          /**
           * Call download function recursively
           */
          download(redirectLocation, {
            output,
            onStart,
            onProgress
          })
            .then(y)
            .catch(n);
        } else {
          n('Server responded with unhandled status: ' + res.statusCode);
        }
      }
    );

    req.end('done');
    req.on('error', err => n(err));
  });
}
201413
function(callback)
    {
        if (this._limit != null && this.offset >= this._limit)
        {
            return callback(null, null);
        }

        var self = this;
        var _next = function(err)
        {       
            if (err)
            {
                return callback(err);
            }
        
            if (self.pos < self.data.length)
            {
                var itemData = self.data[self.pos];
                self.pos++;
                self.offset++;
                var cls = self.itemCls;
                callback(null, new cls(self.api, itemData, true));
            }
            else
            {
                callback(null, null);
            }
        };
        
        if (this.data == null || this.pos >= this.data.length && this.truncated)
        {
            this.loadNextPage(_next);
        }
        else
        {
            process.nextTick(_next);
        }
    }
1151399
function onResponse( res ) {
		self.res.status = res.statusCode;
		self.res.headers = res.headers;

		// TODO: record headers length

		res.on( 'data', onData );
		res.on( 'end', onEnd );
	}
1088372
function extendedCallback(res) {
        timeline.mark(`end:${id}`);
        // add full response data
        moduleData[id].response = getResDataObject(res);
        // flatten object for easy transformation/filtering later
        moduleData[id] = flatten(moduleData[id], { maxDepth: 5 });
        moduleData[id] = filterData(config, moduleData[id]);

        // if filter function returns falsey value, drop all data completely
        if (typeof moduleData[id] !== 'object') {
          timeline.data = timeline.data.filter(
            d => !new RegExp(id).test(d.name)
          );
          delete moduleData[id];
        }

        if (typeof originalCallback === 'function') {
          return originalCallback.apply(this, [res]);
        }
        return true;
      }
1158600
function(stream, callback) {
                    var content = '';
                    stream.on('data', function(chunk) {
                      content += chunk;
                    });
                    stream.on('end', function() {
                      callback(content);
                    });
                  }