Created
December 27, 2010 18:32
-
-
Save jpmckinney/756391 to your computer and use it in GitHub Desktop.
Unpack and beautify JavaScript from command-line
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
// blog post: http://blog.slashpoundbang.com/post/2488598258/running-javascript-from-the-command-line-with-v8 | |
#include <v8.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include "beautify.h" | |
#include "unpack_and_beautify.h" | |
#define BUF_SIZE 1024 | |
using namespace v8; | |
Handle<String> readFile(const char* name) { | |
FILE *file = stdin; | |
int len = 0; | |
char *buf; | |
Handle<String> result; | |
if (name) { | |
file = fopen(name, "rb"); | |
if (file == NULL) { | |
return Handle<String>(); | |
} | |
fseek(file, 0, SEEK_END); | |
len = ftell(file); | |
rewind(file); | |
buf = new char[len + 1]; | |
buf[len] = '\0'; | |
fread(buf, 1, len, file); | |
fclose(file); | |
result = String::New(buf); | |
delete[] buf; | |
} | |
else { | |
char c; | |
buf = (char*)malloc(BUF_SIZE + 1); | |
int buf_size = BUF_SIZE + 1; | |
while ((c = getchar()) != EOF) { | |
buf[len++] = c; | |
if (len == buf_size) { | |
buf_size <<= 1; | |
buf = (char*)realloc(buf, buf_size); | |
} | |
} | |
buf[len] = '\0'; | |
result = String::New(buf); | |
free(buf); | |
} | |
return result; | |
} | |
int main(int argc, char* argv[]) { | |
HandleScope handle_scope; | |
Handle<String> source = readFile(argv[1]); | |
Handle<ObjectTemplate> global = ObjectTemplate::New(); | |
global->Set("source", source); | |
Persistent<Context> context = Context::New(NULL, global); | |
Context::Scope context_scope(context); | |
Handle<Script> beautifyScript = Script::Compile(String::New(beautify_code)); | |
beautifyScript->Run(); | |
Handle<Script> unpackScript = Script::Compile(String::New(unpack_code)); | |
unpackScript->Run(); | |
Handle<Script> runnerScript = Script::Compile(String::New("unpack_and_beautify(source);")); | |
Handle<Value> result = runnerScript->Run(); | |
context.Dispose(); | |
if (!result.IsEmpty() && !result->IsUndefined()) { | |
String::Utf8Value str(result); | |
fprintf(stdout, "%s\n", *str); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment