Using d8
d8
is V8’s own developer shell.
d8
is useful for running some JavaScript locally or debugging changes you have made to V8. Building V8 using GN for x64 outputs a d8
binary in out.gn/x64.optdebug/d8
. You can call d8
with the --help
argument for more information about usage and flags.
Print to the command line #
Printing output is probably going to be very important if you plan to use d8
to run JavaScript files rather than interactively. This can be achieved using console.log
:
$ cat test.js
console.log('Hello world!');
$ out.gn/x64.optdebug/d8 test.js
Hello world!
d8
also comes with a global print
function that does the same thing. However, console.log
is preferred over print
since it works in web browsers as well.
Using read()
you can store the contents of a file into a variable.
d8> const license = read('LICENSE');
d8> license
"This license applies to all parts of V8 that are not externally
maintained libraries. The externally maintained libraries used by V8
are:
… (etc.)"
Use readline()
to interactively enter text:
d8> const greeting = readline();
Welcome
d8> greeting
"Welcome"
Load external scripts #
load()
runs another JavaScript file in the current context, meaning that you can then access anything declared in that file.
$ cat util.js
function greet(name) {
return 'Hello, ' + name;
}
$ d8
d8> load('util.js');
d8> greet('World!');
"Hello, World!"
Pass flags into JavaScript #
It’s possible to make command-line arguments available to your JavaScript code at runtime with d8
. Just pass them after --
on the command line. You can then access them at the top-level of your script using the arguments
object.
out.gn/x64.optdebug/d8 -- hi
You can now access an array of the arguments using the arguments
object:
d8> arguments[0]
"hi"
More resources #
Kevin Ennis’s D8 Guide has really good information about exploring V8 using d8
.
Background of the name d8
: very early on, V8 had a “sample shell”, whose purpose was to demonstrate how V8 could be embedded to build a JavaScript shell. It was intentionally minimalist, and was simply called “shell”. Soon after, a “developer shell” was added with more convenience features to aid developers in their daily work, and it needed a name too. The original reason why “d8” was chosen as a name is lost to history; it caught on because “eveloper” is 8 omitted characters, so “d8 shell” makes sense as an abbreviation, and also fits in nicely with “V8” as the project name.