A Dart File Server in 10 lines

Jeff Heisler
2 min readFeb 4, 2022
Alfred Pennywise (Bateman’s Butler)

Background:

I have been locked into Flutter Web for going on two years. What a ride it’s been. But we aren’t here for that…

Thought web apps had served me well, a dropped network during a performance left me rethinking the whole process. Then it struck me, why not just run the web app locally.

I know, I know, why do you need a web app if you still need files? Well, the web app plays sound files when called upon, but it needs to be available everywhere, on all devices. It’s a script tool for actors, and it’s used to run shows. Sound effects are crucial, but so is the ability for actors to get real time updates to scripts. The web serves that purpose, but with live theater, anything can and will happen. As did to us in Christmas of 2021. We lost the network, and all sound files for our completely scored Christmas Carol. I vowed to never let that happen again.

But, I didn’t want to make big changes to the web app.

Limitations:

It’s just not a simple thing to use a web app to play sound files from the local machine. Sure, I could spin off a simple file server, but I really wanted something I completely controlled. I know Flutter, so they say that means I know Dart.

Enter Alfred:

I looked around and found what must be the simplest web server package for Dart there could ever be.

https://pub.dev/packages/alfred

It’s lightweight, I believe the whole package is still under 200 lines of code, and there are ample examples. Never dabbled in expressJS web servers, I had a lot to catch up on right away. 10 lines of code, but it took me a day to figure it all out. Moving forward I’m going to be writing some json stuff and maybe ween my way off of firebase.

The Code:

import ‘dart:io’;
import ‘package:alfred/alfred.dart’;

void main() async {
final app = Alfred();
app.get(‘/file/:name’, (req, res) {
res.setDownload(filename: ‘${req.params[‘name’]}’);
return File(‘${req.params[‘name’]}’);
});

await app.listen(); //Listening on port 3000
}

Call it like this:

http://localhost:3000/file/THE_FULLNAME_OF_THE_FILE

The file name is relative to the folder you are running the server from.

Run it like this:

For windows, open a command prompt, and run:

ScriptServerWindows

For macOS, open a command prompt, and run:

./ScriptServerMacOS

Keep the command prompt open, and you can get any file from the
server

Build it like this:

Use Dart to create your app, code the app, then run:

Windows:

dart compile exe ScriptServerWindows.dart

macOS:

dart compile exe ScriptServerWindows.dart -o ScriptServerMacOS

The difference makes the unextensioned ScriptServerMacOS which needs to be run as ./ScriptServerMacOS.

Final Thoughts:

Now, no matter what mother nature, or the cable company throws at us, the show must go on!!!

--

--

Jeff Heisler

34 years in Software, and I'm just getting started