A quick google search yields at least one tutorial for writing a C++ "Hello World" for node.js, but it's unclear if it's possible to write such an extension using only C. Assuming it is possible, what challenges / limitations would I face?
Node. js is written in C, C++, and JavaScript. Wikipedia defines Node. js as “a packaged compilation of Google's V8 JavaScript engine, the libuv platform abstraction layer, and a core library, which is itself primarily written in JavaScript.”
Module files can have either a . js, . node, or . json file extension.
The easiest way to call compiled C functions from JavaScript is to use ccall() or cwrap() . ccall() calls a compiled C function with specified parameters and returns the result, while cwrap() “wraps” a compiled C function and returns a JavaScript function you can call normally.
In contrast, JavaScript has no compilation step. Instead, an interpreter in the browser reads over the JavaScript code, interprets each line, and runs it. More modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.
You can write parts of your extension in C if you want, but you'll need at least a small bit of C++ code to glue together your C code with Node.
As you will have seen in your HelloWorld, extensions rely on the v8.h
and node.h
headers, which have all of the classes that Node expects. Without those, you won't be able to properly create the JS object to export back to Node.
That said, you can pretty easily just write a small set of C++ functions that just call C functions, and wrap some kind of C structure.
Found this on Hacker News:
https://github.com/wesolows/v8plus
v8+: Node addon C++ to C boundary
This layer offers a way to write at least simple Node addons in C without all the horrible C++ goop you'd otherwise be expected to use. That goop still exists, but you don't have to write it. More importantly, you can write your module in a sane programming environment, avoiding the confusing and error-prone C++ semantics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With