Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write a node.js extension in C (not C++)?

Tags:

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?

like image 460
noahlz Avatar asked May 06 '12 14:05

noahlz


People also ask

Is Node.js written in C?

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.”

What is the extension of Node.js file?

Module files can have either a . js, . node, or . json file extension.

Can you run C code in JavaScript?

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.

Does JavaScript get compiled to C?

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.


2 Answers

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.

like image 163
loganfsmyth Avatar answered Sep 18 '22 00:09

loganfsmyth


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.

like image 39
noahlz Avatar answered Sep 20 '22 00:09

noahlz