Skip to content

Instantly share code, notes, and snippets.

@loic-sharma
Created January 29, 2018 00:36
Show Gist options
  • Save loic-sharma/321dfdf371e1646458d95d7c4f37ec52 to your computer and use it in GitHub Desktop.
Save loic-sharma/321dfdf371e1646458d95d7c4f37ec52 to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:async/async.dart';
import 'package:watcher/watcher.dart';
watchCurrentDirectory(List<String> arguments) async {
var watcher = new DirectoryWatcher(Directory.current.path);
while (true) {
print("Starting webserver...");
var process = await Process.start('dart', arguments);
await for (var event in StreamGroup.merge([watcher.events, process.stdout])) {
if (event is WatchEvent) {
print("Restarting...");
process.kill();
break;
}
else if (event is List<int>) {
print(UTF8.decode(event));
}
}
}
}
Future startServer() async {
var counter = 0;
var server = await HttpServer.bind(
InternetAddress.LOOPBACK_IP_V4,
4040);
print('listening on localhost:${server.port}');
server.listen((HttpRequest request) {
print("Counter: $counter");
request.response
..write('Test, world! $counter')
..close();
counter++;
});
}
main(List<String> arguments) async {
if (arguments.length > 0 && arguments[0] == "watch")
{
var watchArguments = arguments.sublist(1)
..insert(0, Platform.script.toFilePath());
watchCurrentDirectory(watchArguments);
}
else
{
await startServer();
}
}
@loic-sharma
Copy link
Author

loic-sharma commented Jan 29, 2018

pubspec.yaml:

name: my_app
dependencies:
  watcher: ^0.9.7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment