Revision 63a9cd38 src/node.cc

View differences:

src/node.cc
1 1
#include "node.h"
2 2

  
3
#include "node_tcp.h"
3
//#include "net.h"
4
#include "file.h"
5
#include "process.h"
4 6
#include "node_http.h"
5 7
#include "node_timer.h"
6 8

  
9
#include "natives.h" 
10

  
7 11
#include <stdio.h>
8 12
#include <assert.h>
9 13

  
......
12 16
#include <map>
13 17

  
14 18
using namespace v8;
19
using namespace node;
15 20
using namespace std;
16 21

  
17 22
static int exit_code = 0;
18 23

  
19
// Reads a file into a v8 string.
20
static Handle<String>
21
ReadFile (const string& name) 
24
// Extracts a C string from a V8 Utf8Value.
25
const char*
26
ToCString(const v8::String::Utf8Value& value)
22 27
{
28
  return *value ? *value : "<string conversion failed>";
29
}
23 30

  
24
  FILE* file = fopen(name.c_str(), "rb");
25
  if (file == NULL) return Handle<String>();
31
void
32
ReportException(v8::TryCatch* try_catch)
33
{
34
  v8::HandleScope handle_scope;
35
  v8::String::Utf8Value exception(try_catch->Exception());
36
  const char* exception_string = ToCString(exception);
37
  v8::Handle<v8::Message> message = try_catch->Message();
38
  if (message.IsEmpty()) {
39
    // V8 didn't provide any extra information about this error; just
40
    // print the exception.
41
    printf("%s\n", exception_string);
42
  } else {
43
    message->PrintCurrentStackTrace(stdout);
44

  
45
    // Print (filename):(line number): (message).
46
    v8::String::Utf8Value filename(message->GetScriptResourceName());
47
    const char* filename_string = ToCString(filename);
48
    int linenum = message->GetLineNumber();
49
    printf("%s:%i: %s\n", filename_string, linenum, exception_string);
50
    // Print line of source code.
51
    v8::String::Utf8Value sourceline(message->GetSourceLine());
52
    const char* sourceline_string = ToCString(sourceline);
53
    printf("%s\n", sourceline_string);
54
    // Print wavy underline (GetUnderline is deprecated).
55
    int start = message->GetStartColumn();
56
    for (int i = 0; i < start; i++) {
57
      printf(" ");
58
    }
59
    int end = message->GetEndColumn();
60
    for (int i = start; i < end; i++) {
61
      printf("^");
62
    }
63
    printf("\n");
64
  }
65
}
66

  
67
// Executes a string within the current v8 context.
68
Handle<Value>
69
ExecuteString(v8::Handle<v8::String> source,
70
              v8::Handle<v8::Value> filename)
71
{
72
  HandleScope scope;
73
  Handle<Script> script = Script::Compile(source, filename);
74
  if (script.IsEmpty()) {
75
    return ThrowException(String::New("Error compiling string"));
76
  }
77

  
78
  Handle<Value> result = script->Run();
79
  if (result.IsEmpty()) {
80
    return ThrowException(String::New("Error running string"));
81
  }
82

  
83
  return scope.Close(result);
84
}
85

  
86
JS_METHOD(print) 
87
{
88
  if (args.Length() < 1) return v8::Undefined();
89
  HandleScope scope;
90
  Handle<Value> arg = args[0];
91
  String::Utf8Value value(arg);
92

  
93
  printf("%s\n", *value);
94
  fflush(stdout);
95

  
96
  return Undefined();
97
}
98

  
99

  
100
JS_METHOD(cat) 
101
{
102
  if (args.Length() < 1) return v8::Undefined();
103
  HandleScope scope;
104

  
105
  String::Utf8Value filename(args[0]);
106

  
107
  Local<String> error_msg = String::New("File I/O error");
108

  
109
  FILE* file = fopen(*filename, "rb");
110
  if (file == NULL) {
111
    // Raise error
112
    perror("fopen()");
113
    return ThrowException(error_msg);
114
  }
26 115
 
27
  fseek(file, 0, SEEK_END);
116
  int r = fseek(file, 0, SEEK_END);
117
  if (r < 0) {
118
    perror("fseek()");
119
    return ThrowException(error_msg);
120
  }
121

  
28 122
  int size = ftell(file);
123
  if (size < 0) {
124
    perror("ftell()");
125
    return ThrowException(error_msg);
126
  }
29 127
  rewind(file);
30 128

  
31 129
  char chars[size+1];
......
34 132
    int read = fread(&chars[i], 1, size - i, file);
35 133
    if(read <= 0) {
36 134
      perror("read()");
135
      return ThrowException(error_msg);
37 136
    }
38 137
    i += read;
39 138
  }
......
45 144

  
46 145
  fclose(file);
47 146

  
48
  HandleScope scope;
49
  Local<String> result = String::New(expanded_base, size);
147
  Local<String> contents = String::New(expanded_base, size);
50 148

  
51
  return scope.Close(result);
149
  return scope.Close(contents);
52 150
}
53 151

  
54
static Handle<Value>
55
Log (const Arguments& args) 
152
JS_METHOD(exec) 
56 153
{
57
  if (args.Length() < 1) return v8::Undefined();
154
  if (args.Length() < 2) 
155
    return Undefined();
156

  
58 157
  HandleScope scope;
59
  Handle<Value> arg = args[0];
60
  String::Utf8Value value(arg);
61 158

  
62
  printf("%s\n", *value);
63
  fflush(stdout);
159
  Local<String> source = args[0]->ToString();
160
  Local<String> filename = args[1]->ToString();
64 161

  
65
  return Undefined();
162
  Handle<Value> result = ExecuteString(source, filename);
163
  
164
  return scope.Close(result);
66 165
}
67 166

  
68 167

  
69
static Handle<Value>
70
BlockingFileRead (const Arguments& args)
71
{
72
  if (args.Length() < 1) return v8::Undefined();
73
  HandleScope scope;
74

  
75
  String::Utf8Value filename(args[0]);
76
  Handle<String> output = ReadFile (*filename);
77
  return scope.Close(output);
78
}
79

  
80 168
static void
81 169
OnFatalError (const char* location, const char* message)
82 170
{
......
85 173
}
86 174

  
87 175

  
88
// Extracts a C string from a V8 Utf8Value.
89
const char* ToCString(const v8::String::Utf8Value& value) {
90
  return *value ? *value : "<string conversion failed>";
91
}
92

  
93
void ReportException(v8::TryCatch* try_catch) {
94
  v8::HandleScope handle_scope;
95
  v8::String::Utf8Value exception(try_catch->Exception());
96
  const char* exception_string = ToCString(exception);
97
  v8::Handle<v8::Message> message = try_catch->Message();
98
  if (message.IsEmpty()) {
99
    // V8 didn't provide any extra information about this error; just
100
    // print the exception.
101
    printf("%s\n", exception_string);
102
  } else {
103
    message->PrintCurrentStackTrace(stdout);
104

  
105
    // Print (filename):(line number): (message).
106
    v8::String::Utf8Value filename(message->GetScriptResourceName());
107
    const char* filename_string = ToCString(filename);
108
    int linenum = message->GetLineNumber();
109
    printf("%s:%i: %s\n", filename_string, linenum, exception_string);
110
    // Print line of source code.
111
    v8::String::Utf8Value sourceline(message->GetSourceLine());
112
    const char* sourceline_string = ToCString(sourceline);
113
    printf("%s\n", sourceline_string);
114
    // Print wavy underline (GetUnderline is deprecated).
115
    int start = message->GetStartColumn();
116
    for (int i = 0; i < start; i++) {
117
      printf(" ");
118
    }
119
    int end = message->GetEndColumn();
120
    for (int i = start; i < end; i++) {
121
      printf("^");
122
    }
123
    printf("\n");
124
  }
125
}
126

  
127 176
void
128 177
node_fatal_exception (TryCatch &try_catch)
129 178
{
......
132 181
  exit_code = 1;
133 182
}
134 183

  
135

  
136
// Executes a string within the current v8 context.
137
bool ExecuteString(v8::Handle<v8::String> source,
138
                   v8::Handle<v8::Value> name,
139
                   bool print_result,
140
                   bool report_exceptions) {
141
  v8::HandleScope handle_scope;
142
  v8::TryCatch try_catch;
143
  v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
144
  if (script.IsEmpty()) {
145
    // Print errors that happened during compilation.
146
    if (report_exceptions)
147
      ReportException(&try_catch);
148
    return false;
149
  } else {
150
    v8::Handle<v8::Value> result = script->Run();
151
    if (result.IsEmpty()) {
152
      // Print errors that happened during execution.
153
      if (report_exceptions)
154
        ReportException(&try_catch);
155
      return false;
156
    } else {
157
      if (print_result && !result->IsUndefined()) {
158
        // If all went well and the result wasn't undefined then print
159
        // the returned value.
160
        v8::String::Utf8Value str(result);
161
        const char* cstr = ToCString(str);
162
        printf("%s\n", cstr);
163
      }
164
      return true;
165
    }
166
  }
184
void node_exit (int code)
185
{
186
  exit_code = code;
187
  ev_unloop(node_loop(), EVUNLOOP_ALL);
167 188
}
168 189

  
169
// The callback that is invoked by v8 whenever the JavaScript 'load'
170
// function is called.  Loads, compiles and executes its argument
171
// JavaScript file.
172
v8::Handle<v8::Value> Load(const v8::Arguments& args) {
173
  for (int i = 0; i < args.Length(); i++) {
174
    v8::HandleScope handle_scope;
175
    v8::String::Utf8Value file(args[i]);
176
    if (*file == NULL) {
177
      return v8::ThrowException(v8::String::New("Error loading file"));
178
    }
179
    v8::Handle<v8::String> source = ReadFile(*file);
180
    if (source.IsEmpty()) {
181
      return v8::ThrowException(v8::String::New("Error loading file"));
182
    }
183
    if (!ExecuteString(source, v8::String::New(*file), false, true)) {
184
      return v8::ThrowException(v8::String::New("Error executing file"));
185
    }
186
  }
187
  return v8::Undefined();
188
}
189 190

  
190 191
static ev_async thread_pool_watcher;
191 192

  
......
212 213
int
213 214
main (int argc, char *argv[]) 
214 215
{
216
  // start eio thread pool
217
  ev_async_init(&thread_pool_watcher, thread_pool_cb);
218
  eio_init(thread_pool_want_poll, NULL);
219

  
215 220
  V8::SetFlagsFromCommandLine(&argc, argv, true);
216 221

  
217
  if(argc != 2)  {
222
  if(argc < 2)  {
218 223
    fprintf(stderr, "No script was specified.\n");
219 224
    return 1;
220 225
  }
221 226

  
222

  
223 227
  string filename(argv[1]);
224 228

  
225 229
  HandleScope handle_scope;
226 230

  
227 231
  Persistent<Context> context = Context::New(NULL, ObjectTemplate::New());
228 232
  Context::Scope context_scope(context);
233
  V8::SetFatalErrorHandler(OnFatalError);
229 234

  
230 235
  Local<Object> g = Context::GetCurrent()->Global();
231 236

  
232
  g->Set ( String::New("log")
233
         , FunctionTemplate::New(Log)->GetFunction()
234
         );
237
  Local<Object> node = Object::New();
238
  g->Set(String::New("node"), node);
235 239

  
236
  g->Set ( String::New("load")
237
         , FunctionTemplate::New(Load)->GetFunction()
238
         );
240
  Local<Object> blocking = Object::New();
241
  node->Set(String::New("blocking"), blocking);
239 242

  
240
  g->Set ( String::New("blockingFileRead")
241
         , FunctionTemplate::New(BlockingFileRead)->GetFunction()
242
         );
243
  JS_SET_METHOD(blocking, "exec", exec);
244
  JS_SET_METHOD(blocking, "cat", cat);
245
  JS_SET_METHOD(blocking, "print", print);
243 246

  
247
  Local<Array> arguments = Array::New(argc);
248
  for (int i = 0; i < argc; i++) {
249
    Local<String> arg = String::New(argv[i]);
250
    arguments->Set(Integer::New(i), arg);
251
  }
252
  g->Set(String::New("ARGV"), arguments);
253

  
254
  // BUILT-IN MODULES
244 255
  Init_timer(g);
245
  Init_tcp(g);
256
  //NodeInit_net(g);
257
  NodeInit_process(g);
258
  NodeInit_file(g);
246 259
  Init_http(g);
247 260

  
248
  V8::SetFatalErrorHandler(OnFatalError);
249

  
250
  v8::Handle<v8::String> source = ReadFile(filename);
251

  
252
  // start eio thread pool
253
  ev_async_init(&thread_pool_watcher, thread_pool_cb);
254
  ev_async_start(EV_DEFAULT_ &thread_pool_watcher);
255
  eio_init(thread_pool_want_poll, NULL);
256

  
257
  ExecuteString(source, String::New(filename.c_str()), false, true);
261
  // NATIVE JAVASCRIPT MODULES
262
  TryCatch try_catch;
263
  Handle<Value> result = ExecuteString(String::New(native_main), 
264
                                       String::New("main.js"));
265
  if (try_catch.HasCaught()) {
266
    ReportException(&try_catch);
267
    return 1;
268
  }
258 269

  
259 270
  ev_loop(node_loop(), 0);
260 271

  
......
262 273

  
263 274
  return exit_code;
264 275
}
265

  

Also available in: Unified diff