Skip to content

Instantly share code, notes, and snippets.

@Qowyn
Created August 25, 2016 14:13
Show Gist options
  • Save Qowyn/171fb660dfa81b8d46a009b6373432d1 to your computer and use it in GitHub Desktop.
Save Qowyn/171fb660dfa81b8d46a009b6373432d1 to your computer and use it in GitHub Desktop.
Java-Nashorn based file watcher, execute tasks on file creation/rename
#!/usr/bin/jjs -scripting
if ($ARG.length < 2) {
print("Usage: jjs -scripting watch.js -- <fileToWatch> <command> [args]");
exit();
}
var FileSystems = Java.type("java.nio.file.FileSystems");
var StandardWatchEventKinds = Java.type("java.nio.file.StandardWatchEventKinds");
var Runtime = Java.type("java.lang.Runtime");
var fileToWatch = FileSystems.default.getPath($ARG[0]);
var file = fileToWatch.fileName;
var directory = fileToWatch.parent;
if (directory === null) {
print("Usage: jjs -scripting watch.js -- <fileToWatch> <command> [args]");
exit();
}
var progArgs = $ARG.slice(1);
var watcher = FileSystems.default.newWatchService();
directory.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
for (;;) {
var key = watcher.take();
for each (event in key.pollEvents()) {
if (event.kind() === StandardWatchEventKinds.ENTRY_CREATE) {
if (event.context().equals(file)) {
Runtime.runtime.exec(progArgs);
}
}
}
var valid = key.reset();
if (!valid) {
exit();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment