Compile JavaScript to Native Code with V8
Asked Answered
P

4

26

Is it really possible, with Google's V8 Engine, to compile JavaScript into Native Code, save it as a binary file, and execute it whenever I want through my software envorinment, on any machine?

Piled answered 2/6, 2010 at 22:58 Comment(1)
#1152867Geriatrics
S
27

You can use the V8 snapshot functionality to precompile the code. This still means that you have to have a full version of V8 running to load the snapshot (i.e., you don't get stand-alone native code, it needs to run inside the V8 VM), so all you save is the compilation time. Also, the quality of snapshot code isn't necessarily as good as JIT'ed code because JIT code can use, e.g., SSE2/SSE3 if it's available, which snapshots can't assume.

Sunnisunnite answered 22/6, 2010 at 12:40 Comment(0)
C
4

As far as I know, V8 is purely a just-in-time compiler, and does not have an ahead-of-time option.

As discussed at the articles I linked, JITs allow better, more flexible optimizations.

Carpi answered 2/6, 2010 at 23:2 Comment(1)
BUT a JIT must finish the task in a timely manner. Therefore they must avoid costly (time and resources like memory) operations.Rheostat
A
4

Instead, it might be possible to use a .NET JavaScript/JScript compiler to create a .NET exe, then convert the .NET exe to a native .exe using the Mono ahead-of-time compiler.

Anglim answered 3/6, 2010 at 0:0 Comment(1)
Just as a note to whoever didn't yet try Mono AOT and was super hyped up as I was: it doesn't support Windows. It does run on any Linux though, so who knows, maybe this will change.Griggs
P
1

The closest you might get to acheiving your goal is to create a self-executing Javascript bytecode wrapper.

A project that does this is pkg

It somehow creates a self-contained binary executable from Javascript, including module dependencies and asset files and produces a self-contained executable.

Installation and use is easy:

$ npm install -g pkg
$ pkg index.js -o my-program
$ ./my-program

My understanding is that this binary contains nodejs bytecode. It also appears that you can cross-compile.

Note: I've tried ncc and nexe also, but I haven't found them to be as useful. ncc just creates a self-contained Javascript file and nexe encountered a Python error when I tried to use it.

Presage answered 13/11, 2021 at 13:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.