DEV Community

Cover image for V8.js - Access native v8 engine function from Javascript
Guillaume Martigny
Guillaume Martigny

Posted on

V8.js - Access native v8 engine function from Javascript

When Google decide to create his own web browser, their engineers build a brand new Javascript engine. Build for speed and memory performance, its adoption into Node.js makes it the most influential engine out there.

A few things was impossible to do in Javascript. Specifically discussing with the engine itself and make use of its native methods. Getting a precise measure of the heap memory size (only possible on Chrome), triggering the garbage collector or getting the optimisation status of a function was inaccessible to Javascripts devs.

Not anymore.

V8.js

Using the flag --allow-natives-syntax on execution now allow you to call all V8's native methods. Since the syntaxe can still be a bit clanky, V8.js wrap it around a more classic library interface.

Install

Like any other library available on NPM, you can install V8.js with one command line:

$ npm install v8.js
Enter fullscreen mode Exit fullscreen mode

Or add a <script> tag in your HTML page:

<script src="https://unpkg.com/v8.js"></script>
<!-- Or -->
<script src="https://cdn.jsdelivr.net/npm/v8.js"></script>
Enter fullscreen mode Exit fullscreen mode

Usage

Once installed, V8.js can be required and expose a list of functions for you to use.

const v8 = require("v8.js"); // Only for node

v8.getHeapUsage();
Enter fullscreen mode Exit fullscreen mode

Example

const v8 = require("v8.js");

const previousUsage = v8.getHeapUsage();
v8.collectGarbage();
const afterUsage = v8.getHeapUsage();

console.log(`Just cleared ${previousUsage - afterUsage} bytes of memory.`);
Enter fullscreen mode Exit fullscreen mode

I need you !

I still consider it a beta version (hence the v0.2.0 version). So I'll warmly welcome any feedback.

The list of available functions of the v8 engine is quite large and I didn't want to include everything blindly. So if you see something useful V8.js is missing raise a new issue with your use-case.

Peace ✌️

Top comments (0)