root/lang/cplusplus/llv8call/trunk/ext/fs/fs.cc @ 20522

Revision 20522, 2.3 kB (checked in by tokuhirom, 6 years ago)

- Merge //mirror/coderepos/lang/cplusplus/llv8call/branches/stdlib to //mirror/coderepos/lang/cplusplus/llv8call/trunk

Line 
1#include <v8.h>
2#include <cstring>
3#include "v8ext.h"
4#include <nspr/nspr.h>
5
6using namespace v8;
7
8void setup_file(v8::Handle<v8::Object> global);
9/*
10void setup_dir(v8::Handle<v8::Object> global);
11*/
12
13V8EXTINIT_FUNC
14Handle<Value> instantiate() {
15    HandleScope hs;
16    Handle<Object> obj = Object::New();
17    setup_file(obj);
18    /*
19    setup_dir(obj);
20    */
21    return obj;
22}
23
24// Executes a string within the current v8 context.
25bool Exec(v8::Handle<v8::String> source,
26               v8::Handle<v8::Value> name,
27               bool print_result) {
28    v8::HandleScope handle_scope;
29    v8::TryCatch try_catch;
30    try_catch.SetVerbose(true);
31    v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
32    if (script.IsEmpty()) {
33        // Print errors that happened during compilation.
34        v8::String::Utf8Value error(try_catch.Exception());
35        printf("%s\n", *error);
36        return false;
37    } else {
38        v8::Handle<v8::Value> result = script->Run();
39        if (result.IsEmpty()) {
40            // Print errors that happened during execution.
41            v8::String::Utf8Value error(try_catch.Exception());
42            printf("%s\n", *error);
43            return false;
44        } else {
45            if (print_result && !result->IsUndefined()) {
46                // If all went well and the result wasn't undefined then print
47                // the returned value.
48                v8::String::AsciiValue str(result);
49                printf("%s\n", *str);
50            }
51            return true;
52        }
53    }
54}
55
56v8::Handle<v8::String> ReadFile(const char* name) {
57    FILE* file = fopen(name, "rb");
58    if (file == NULL) return v8::Handle<v8::String>();
59
60    fseek(file, 0, SEEK_END);
61    int size = ftell(file);
62    rewind(file);
63
64    char* chars = new char[size + 1];
65    char *buffer;
66    chars[size] = '\0';
67    for (int i = 0; i < size;) {
68        int read = fread(&chars[i], 1, size - i, file);
69        i += read;
70    }
71    fclose(file);
72    if (size>2 && chars[0] == '#' && chars[1] == '!') {
73        // shebang hack
74        char *end = strchr(chars, '\n');
75        if (end && end-chars > 0) {
76            size -= (end-chars) + 1;
77            buffer = end+1;
78        }
79    } else {
80        buffer = chars;
81    }
82    v8::Handle<v8::String> result = v8::String::New(buffer, size);
83    delete[] chars;
84    return result;
85}
86
Note: See TracBrowser for help on using the browser.