http functions in V8 javascript engine
Asked Answered
F

3

5

I want to use the V8 javascript engine standalone, e.g. I will run it in command line as explained here:

$> ./v8-shell -e 'print("10*10 = " + 10*10)'

I want the javascript to perform some http requests, preferably using jQuery APIs but XMLHttpRequest is also ok.

Is there any built in method in V8 to do this? If not is there any way to achieve it without implementing accessors/cpp extensions?

Fibrinolysis answered 1/12, 2011 at 1:12 Comment(1)
Can you do a system call to something like curl or wget from inside V8?Bordeaux
D
6

Is there any built in method in V8 to do this?

Not in V8 directly, but there is NodeJS that adds network and file system functionality, among other features.

To steal an example from the documentation:

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {

     // callback invoked when response is received
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');

  res.on('data', function (chunk) {

      // 'data' event is fired whenever a chunk of the response arrives
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
Doriedorin answered 1/12, 2011 at 1:29 Comment(0)
M
3

V8 is just a javascript engine, it doesn't have browser host methods like alert or host objects like XMLHttpRequest.

Motive answered 1/12, 2011 at 1:25 Comment(0)
V
3

Here's a good example: when you use Node's vm.createContext() method, basically a direct binding to V8 functionality, here's what that global context has:

  Errors:     [Error, EvalError, RangeError, ReferenceError,
               SyntaxError, TypeError, URIError],

  Types:      [Array, Boolean, Date, Function, Map, Number,
               Object, Proxy, RegExp, Set, String, WeakMap], //--harmony: [Map, Proxy, Set, WeakMap]


  Primitives: [Infinity, NaN, undefined],

  Dicts:      [Math, JSON],

  Methods:    [decodeURI, decodeURIComponent, encodeURI, encodeURIComponent,
               escape, eval, isFinite, isNaN, parseFloat, parseInt, unescape]

It doesn't even have set/clearTimeout, set/clearInternal (not native javascript functions). JavaScript as a language is much more tightly focused than most realize. It always exists in a host environment that adds more stuff on top.

Vandusen answered 8/12, 2011 at 9:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.