Created
August 25, 2016 14:13
-
-
Save Qowyn/171fb660dfa81b8d46a009b6373432d1 to your computer and use it in GitHub Desktop.
Java-Nashorn based file watcher, execute tasks on file creation/rename
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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