Serve static files from `root`.

@param {String} root
@param {Object} [opts]
@return {Function}
@api public
979116
function serve(root, route, opts) {
  opts = opts || {};
  route = route || '/';
  assert(root, 'root directory is required to serve files');

  // options
  debug('static "%s" "%s" %j', route, root, opts);
  opts.root = resolve(root);
  opts.index = opts.index || 'index.html';

  routes[route] = opts;
  return function *serve(next) {
    yield* next;
    debug('path: "%s"', this.path);
    var route = this.path.split('/')[1] || '/';
    if (this.method != 'HEAD' && this.method != 'GET') return;
    // response is already handled
    if (this.body != null || this.status != 404) return;

    yield send(this, this.path.slice(1 + route.length) || '/', routes[route]);
  };
}
507711
function API(opts) {
  opts = opts || {};

  this.verbose = !!opts.verbose;
  this.request = opts.request || request;
  this.baseUrl = opts.baseUrl || BASE_URL;
  var parsedUrl = url.parse(this.baseUrl);
  this.basePath = parsedUrl.path;
  this.baseHost = parsedUrl.protocol + '//' + parsedUrl.host;
  this.timeout = opts.timeout || 50000;

  if (this.verbose) {
    log.setLevel('debug');
  } else {
    log.setLevel('info');
  }
}
1156816
function getRoot(term, opts) {
  var parts = term.split(path.sep);
  var root = parts.shift() || path.sep; // Windows support, I hope?

  // Last section treated as term if not suffixed by path separator.
  for(var i = 0; i < parts.length - 1; i++) {
    var tryPath = path.join(root, parts[i]);
    try {
      var stat = fs.statSync(tryPath);
      if(!stat.isDirectory()) {
        break;
      }
    } catch (e) {
      if(e.code === 'ENOENT') {
        break;
      }
      throw e;
    }
    root = tryPath;
  }
  root = util.normalizePath(root);
  return root;
}
546321
function findFile(root, filename) {
    return Q.nfcall(fs.readdir, root)
    .then(function(files) {
        return _.find(files, function(file) {
            return (file.toLowerCase() == filename.toLowerCase());
        });
    });
}
741977
function serveStatic(options) {
    var opts = options || {};

    if (typeof opts.appendRequestPath === 'undefined') {
        opts.appendRequestPath = true;
    }

    assert.object(opts, 'options');
    assert.string(opts.directory, 'options.directory');
    assert.optionalNumber(opts.maxAge, 'options.maxAge');
    assert.optionalObject(opts.match, 'options.match');
    assert.optionalString(opts.charSet, 'options.charSet');
    assert.optionalString(opts.file, 'options.file');
    assert.bool(opts.appendRequestPath, 'options.appendRequestPath');

    var p = path.normalize(opts.directory).replace(/\\/g, '/');
    var re = new RegExp('^' + escapeRE(p) + '/?.*');

    function serveFileFromStats(file, err, stats, isGzip, req, res, next) {

        if (typeof req.connectionState === 'function' &&
            (req.connectionState() === 'close' ||
            req.connectionState() === 'aborted')) {
            next(false);
            return;
        }

        if (err) {
            next(new ResourceNotFoundError(err, '%s', req.path()));
            return;
        } else if (!stats.isFile()) {
            next(new ResourceNotFoundError('%s does not exist', req.path()));
            return;
        }

        if (res.handledGzip && isGzip) {
            res.handledGzip();
        }

        var fstream = fs.createReadStream(file + (isGzip ? '.gz' : ''));
        var maxAge = opts.maxAge === undefined ? 3600 : opts.maxAge;
        fstream.once('open', function (fd) {
            res.cache({maxAge: maxAge});
            res.set('Content-Length', stats.size);
            res.set('Content-Type', mime.lookup(file));
            res.set('Last-Modified', stats.mtime);

            if (opts.charSet) {
                var type = res.getHeader('Content-Type') +
                    '; charset=' + opts.charSet;
                res.setHeader('Content-Type', type);
            }

            if (opts.etag) {
                res.set('ETag', opts.etag(stats, opts));
            }
            res.writeHead(200);
            fstream.pipe(res);
            fstream.once('close', function () {
                next(false);
            });
        });

        res.once('close', function () {
            fstream.close();
        });
    }

    function serveNormal(file, req, res, next) {
        fs.stat(file, function (err, stats) {
            if (!err && stats.isDirectory() && opts.default) {
                // Serve an index.html page or similar
                var filePath = path.join(file, opts.default);
                fs.stat(filePath, function (dirErr, dirStats) {
                    serveFileFromStats(filePath,
                        dirErr,
                        dirStats,
                        false,
                        req,
                        res,
                        next);
                });
            } else {
                serveFileFromStats(file,
                    err,
                    stats,
                    false,
                    req,
                    res,
                    next);
            }
        });
    }

    function serve(req, res, next) {
        var file;

        if (opts.file) {
            //serves a direct file
            file = path.join(opts.directory,
                decodeURIComponent(opts.file));
        } else {
            if (opts.appendRequestPath) {
                file = path.join(opts.directory,
                    decodeURIComponent(req.path()));
            }
            else {
                var dirBasename = path.basename(opts.directory);
                var reqpathBasename = path.basename(req.path());

                if (path.extname(req.path()) === '' &&
                    dirBasename === reqpathBasename) {

                    file = opts.directory;
                }
                else {
                    file = path.join(opts.directory,
                        decodeURIComponent(path.basename(req.path())));
                }
            }
        }

        if (req.method !== 'GET' && req.method !== 'HEAD') {
            next(new MethodNotAllowedError(req.method));
            return;
        }

        if (!re.test(file.replace(/\\/g, '/'))) {
            next(new NotAuthorizedError('%s', req.path()));
            return;
        }

        if (opts.match && !opts.match.test(file)) {
            next(new NotAuthorizedError('%s', req.path()));
            return;
        }

        if (opts.gzip && req.acceptsEncoding('gzip')) {
            fs.stat(file + '.gz', function (err, stats) {
                if (!err) {
                    res.setHeader('Content-Encoding', 'gzip');
                    serveFileFromStats(file,
                        err,
                        stats,
                        true,
                        req,
                        res,
                        next);
                } else {
                    serveNormal(file, req, res, next);
                }
            });
        } else {
            serveNormal(file, req, res, next);
        }

    }

    return (serve);
}
999195
def serve(self, filename):
        ''''''
        if not self.exists(filename):
            abort(404)
        return self.backend.serve(filename)
196924
function Transport (opts) {
  this.path = opts.path;
  this.host = opts.host;
  this.port = opts.port;
  this.secure = opts.secure;
  this.query = opts.query;
  this.timestampParam = opts.timestampParam;
  this.timestampRequests = opts.timestampRequests;
  this.readyState = '';
}
566286
function Server(srv, opts){
  if (!(this instanceof Server)) return new Server(srv, opts);
  if ('object' == typeof srv && srv instanceof Object && !srv.listen) {
    opts = srv;
    srv = null;
  }
  opts = opts || {};
  this.nsps = {};
  this.parentNsps = new Map();
  this.path(opts.path || '/socket.io');
  this.serveClient(false !== opts.serveClient);
  this.parser = opts.parser || parser;
  this.encoder = new this.parser.Encoder();
  this.adapter(opts.adapter || Adapter);
  this.origins(opts.origins || '*:*');
  this.sockets = this.of('/');
  if (srv) this.attach(srv, opts);
}
1025363
function load(root, path, callback, errback) {
		resolve(root, path, function (realPath, contents) {
			process(realPath, contents, callback, errback);
		}, errback);
	}
188806
function fsReaddirSync(root, files, fp) {
  if (typeof root !== 'string') {
    throw new TypeError('fsReaddir.sync: expect `root` to be string');
  }

  fp = fp || '';
  files = files || [];

  var dir = path.join(root, fp);
  if (fs.statSync(dir).isDirectory()) {
    fs.readdirSync(dir).forEach(function(name) {
      fsReaddirSync(root, files, path.join(dir, name));
    });
  } else {
    files.push(fp);
  }

  return files;
}
1310215
function (opts, cb) {
      var self = this
      opts = opts || {}
      var root = opts.root || RootKey
      var key = opts.key
      if (!key) {
        return cb(new Error(ERR.FA_PARAMS.msg), ERR.FA_PARAMS)
      }
      mq.hget(root, key, function (err, doc) {
        if (err) {
          cb(err, ERR.config.FA_GET_CONFIG)
        } else {
          if (!doc) return cb(null, null)
          doc = self._parse(doc)
          if (doc.err) {
            if (doc === ERR.config.FA_CONFIG_EXPIRED) {
              self.delConfig(opts, function (err, doc) {})
            }
            return cb(new Error(doc.msg), doc)
          }
          cb(null, doc.value)
        }
      })
    }
1256624
function restore(options) {

  var opt = options || Object.create(null);
  if (!opt.uri) {
    throw new Error('missing uri option');
  }
  if (!opt.stream) {
    if (!opt.root) {
      throw new Error('missing root option');
    } else if (!fs.existsSync(opt.root) || !fs.statSync(opt.root).isDirectory()) {
      throw new Error('root option is not a directory');
    }
  }

  var my = {
    dir: path.join(__dirname, 'dump', path.sep),
    uri: String(opt.uri),
    root: path.resolve(String(opt.root)) + path.sep,
    stream: opt.stream || null,
    parser: opt.parser || 'bson',
    callback: typeof opt.callback === 'function' ? opt.callback : null,
    tar: typeof opt.tar === 'string' ? opt.tar : null,
    logger: typeof opt.logger === 'string' ? path.resolve(opt.logger) : null,
    metadata: Boolean(opt.metadata),
    drop: Boolean(opt.drop),
    dropCollections: Boolean(opt.dropCollections) ? opt.dropCollections : null,
    options: typeof opt.options === 'object' ? opt.options : {}
  };
  if (my.stream) {
    my.tar = true; // override
  }
  wrapper(my);
}
1173991
def serve_file(load, fnd):
    '''
    
    '''
    if 'env' in load:
        # "env" is not supported; Use "saltenv".
        load.pop('env')

    ret = {'data': '',
           'dest': ''}

    if 'path' not in load or 'loc' not in load or 'saltenv' not in load:
        return ret

    if 'path' not in fnd or 'bucket' not in fnd:
        return ret

    gzip = load.get('gzip', None)

    # get the saltenv/path file from the cache
    cached_file_path = _get_cached_file_name(
            fnd['bucket'],
            load['saltenv'],
            fnd['path'])

    ret['dest'] = _trim_env_off_path([fnd['path']], load['saltenv'])[0]

    with salt.utils.files.fopen(cached_file_path, 'rb') as fp_:
        fp_.seek(load['loc'])
        data = fp_.read(__opts__['file_buffer_size'])
        if data and six.PY3 and not salt.utils.files.is_binary(cached_file_path):
            data = data.decode(__salt_system_encoding__)
        if gzip and data:
            data = salt.utils.gzip_util.compress(data, gzip)
            ret['gzip'] = gzip
        ret['data'] = data
    return ret
329193
function flattenPath(file, opts) {
  var fileName = path.basename(file.path);
  var dirs;

  if (!opts.includeParents && !opts.subPath) {
    return fileName;
  }

  dirs = path.dirname(file.relative).split(path.sep);
  if (opts.includeParents) {
    dirs = includeParents(dirs, opts.includeParents);
  }
  if (opts.subPath) {
    dirs = subPath(dirs, opts.subPath);
  }

  dirs.push(fileName);
  return path.join.apply(path, dirs);
}
571122
function loadFromOptions(opts) {
  var defCfg = loadDefault()
  var cfg = opts.config ? loadFromFile(opts.config) : loadDefault()

  // Command line config override file loaded config
  for (var k in opts) {
    defCfg.hasOwnProperty(k) && (defCfg[k] !== opts[k] && (cfg[k] = opts[k]))
  }

  return cfg
}
1195978
function serve(req, res, next) {
    if (req.method !== 'GET' && req.method !== 'HEAD') return next();

    // surprisingly (bug?) express does not auto-decode req.path
    var reqPath = decodeURI(req.path);

    var file$ = self.file$;

    // try straight match
    var spo = file$[reqPath];

    if (!spo && !/\/$|\.[^/]+$/.test(reqPath)) {

      // try adding trailing / and redirect if found
      if (self.trailingSlash) {
        var redir = reqPath + '/';
        spo = file$[redir];
        if (spo) {
          debug('static redirect %s %s', reqPath, redir);
          return res.redirect(302, redir); // use 302 to avoid browser redir caching
        }
      }

      // try extensions
      if (!spo && self.extensions) {
        for (var i=0; i<self.extensions.length; i++) {
          if ((spo = file$[reqPath + self.extensions[i]])) break;
        }
      }
    }

    if (!spo) return next(); // give up

    if (self.noHtmlExtensions && !path.extname(spo.file)) {
      res.setHeader('Content-Type', 'text/html; charset=utf-8');
    }

    debug('static %s%s', reqPath, (reqPath !== spo.file ? ' -> ' + spo.file : ''));

    var doit = function() { send(req, spo.file, spo.sp.sendOpts).pipe(res); };

    if (spo.sp.delay) return u.delay(doit, u.ms(spo.sp.delay));

    doit();
  }
419527
function rmdirSync(root) {

  if (typeof root !== 'string') {
    throw new Error('missing root');
  }

  var chunks = root.split(path.sep); // split in chunks
  var chunk = path.resolve(root); // build absolute path
  // remove "/" from head and tail
  if (chunks[0] === '') {
    chunks.shift();
  }
  if (chunks[chunks.length - 1] === '') {
    chunks.pop();
  }

  return rmdirSyncRecursive(chunk, chunks);
}