Skip to content

Instantly share code, notes, and snippets.

@spence
Last active August 29, 2015 14:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spence/30d5aa383fec6be8e51e to your computer and use it in GitHub Desktop.
Save spence/30d5aa383fec6be8e51e to your computer and use it in GitHub Desktop.
Bash PhantomJS REPL modeled after https://github.com/sotownsend/BooJS
#!/usr/bin/env bash
### Repl Usage:
#
# $ ./phantomjs-repl.sh
# > missing
# ReferenceError: Can't find variable: missing
# > window
# [object Window]
# > console.log('Hello')
# Hello
# undefined
# > !jquery-1.11.2.min.js
# Loading jquery-1.11.2.min.js ... done
# > $('<span>Hello</span>').text()
# Hello
# > ^C
#
### Pipes!
#
# $ echo 'console.log("Hello")' | ./phantomjs-repl.sh -
# Hello
# undefined
tmpfile=$(mktemp /tmp/pr-XXXXX)
cat <<EOF >> $tmpfile
var __system = require("system");
phantom.onError = function(msg, trace) {
__system.stderr.writeLine(msg);
phantom.exit(1);
};
var __loadfile = function(filename) {
__system.stdout.write("Loading " + filename + " ... ");
if (phantom.injectJs(filename)) {
__system.stdout.write("done\n");
} else {
__system.stdout.write("failed\n");;
}
};
var __repl = function() {
while (1) {
if ("$1" !== '-') {
__system.stdout.write("> ");
}
var line = __system.stdin.readLine();
if (!line.length && "$1" === '-') {
break;
}
if (line[0] === "!" && line.length > 1) {
__loadfile(line.slice(1));
} else {
try {
var value = eval(line);
if (value === void(0)) {
value = "undefined";
}
__system.stdout.writeLine(value);
} catch (e) {
__system.stdout.writeLine(e);
}
}
}
};
__repl();
phantom.exit(0);
EOF
phantomjs $tmpfile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment