staticFiles method Null safety

Route staticFiles(
  1. String path,
  2. dynamic directory,
  3. {Map<String, String>? pathRegEx,
  4. int statusCode = 200,
  5. String? mimeType,
  6. String? charset = kDefaultCharset,
  7. ResponseProcessor? responseProcessor,
  8. bool stripPrefix = true,
  9. Future<Response> directoryLister(
    1. Directory directory
  10. Iterable<String? Function(File)>? mimeTypeDetectors}

Serves requests for static files at path from directory

stripPrefix parameter determines if the matched part of the path shall be discarded while locating the target file.

When stripPrefix is true, the behaviour is similar to 'alias' in Nginx.

With path '/static/*', the target file will be located inside directory in the following way:

/static/html/index.html -> html/index.html

When stripPrefix is false, the behavior is similar to 'root' in Nginx.

With path '/static/*', the target file will be located inside directory in the following way:

/static/html/index.html -> static/html/index.html

Example: final server = Jaguar(); server.staticFiles('/static/*', 'static'); await server.serve();


Route staticFiles(String path, directory,
    {Map<String, String>? pathRegEx,
    int statusCode = 200,
    String? mimeType,
    String? charset = kDefaultCharset,
    ResponseProcessor? responseProcessor,
    bool stripPrefix = true,
    Future<Response> directoryLister(Directory directory)?,
    Iterable<String? Function(File)>? mimeTypeDetectors}) {
  if (directory is String) directory = Directory(directory);

  final Directory dir = directory;
  if (!dir.existsSync())
    throw Exception('Directory ${dir.path} does not exist!');

  int skipCount = 0;
  Route route = this.get(path, (ctx) async {
    Iterable<String> segs = ctx.pathSegments;
    if (stripPrefix) segs = segs.skip(skipCount);

    String path = p.join(dir.path, p.joinAll(segs));
    var file = File(path);

    if (!await file.exists()) {
      final fileDir = Directory(path);

      if (!await fileDir.exists()) return Response(statusCode: 404);

      path = p.join(path, 'index.html');
      file = File(path);

      if (!await file.exists()) {
        if (directoryLister != null) return directoryLister(fileDir);
        return Response(statusCode: 404);

    return StreamResponse(
        body: await file.openRead(),
        mimeType: MimeTypes.ofFile(file, detectors: mimeTypeDetectors));
      pathRegEx: pathRegEx,
      statusCode: statusCode,
      mimeType: mimeType,
      charset: charset,
      responseProcessor: responseProcessor);

  if (stripPrefix) {
    if (route.pathSegments.isNotEmpty) {
      skipCount = route.pathSegments.length - 1;
  return route;