Home >Web Front-end >JS Tutorial >Use C/C to implement Node.js modules (1)_node.js
A pitfall that occurred a long time ago - using Node.js to reconstruct NBUT's Online Judge, including the evaluation side, also had to be reconstructed. (As for when it will be completed, don’t worry about it, (/‵Д′)/~ ╧╧
In short, what we have to do now is actually to use C/C to implement the Node.js module.
Preparation
If a worker wants to do his job well, he must first~~play a rogue~~ and sharpen his tools.
node-gyp
First you need a node-gyp module.
At any corner, execute:
After a series of blahblahs, you are installed.
Python
Then you need a python environment.
Go to the official website to get one yourself.
Note: According to node-gyp's GitHub, please make sure your python version is between 2.5.0 and 3.0.0.
Compilation environment
Well, I’m just too lazy to write it down in detail. Please go to node-gyp to see the compiler requirements. And pour it well.
Getting Started
Let me just talk about the introductory Hello World on the official website.
Hello World
Please prepare a C file, for example, call it ~~sb.cc~~ hello.cc.
Then let’s go step by step, first create the header file and define the namespace:
Main function
Next we write a function whose return value is Handle
Then let me briefly analyze these things:
Handle
You must have integrity as a human being. I would like to state in advance that I refer to it from here (@fool).
V8 uses the Handle type to host JavaScript objects. Similar to C's std::sharedpointer, assignments between Handle types directly pass object references, but the difference is that V8 uses its own GC to manage the object life cycle, rather than intelligent Commonly used reference counting for pointers.
JavaScript types have corresponding custom types in C, such as String, Integer, Object, Date, Array, etc., which strictly abide by the inheritance relationship in JavaScript. When using these types in C, you must use Handle management to use the GC to manage their life cycle instead of using the native stack and heap.
This so-called Value can be seen from the various inheritance relationships in the header file v8.h of the V8 engine. It is actually the base class of various objects in JavaScript.
After understanding this matter, we can roughly understand the meaning of the above function declaration, which is that we write a Hello function that returns an indefinite type value.
Note: We can only return specific types, namely String, Integer, etc. under the management of Handle.
Arguments
This is the parameter passed into this function. We all know that in Node.js, the number of parameters is random. When these parameters are passed into C, they are converted into objects of this Arguments type.
We will talk about the specific usage later. Here you just need to understand what this is. (Why are you so careful? Because the examples in the official Node.js documentation are discussed separately. I am just talking about the first Hello World example now (´థ౪థ)σ
Contribution
Then we started to add bricks and tiles. Just two simple sentences:
What do these two sentences mean? The rough meaning is to return a string "world" in Node.js.
HandleScope
The same reference comes from here.
The life cycle of Handle is different from that of C smart pointers. It does not exist within the scope of C semantics (that is, the part surrounded by {}), but needs to be manually specified through HandleScope. HandleScope can only be allocated on the stack. After the HandleScope object is declared, the life cycle of the Handle created subsequently is managed by HandleScope. After the HandleScope object is destructed, the Handle managed by it will be judged by the GC whether to be recycled.
So, we have to declare this Scope when we need to manage its life cycle. Okay, so why doesn't our code look like this?
Because when the function returns, the scope will be destructed and the Handles it manages will also be recycled, so this String will become meaningless.
So V8 came up with a magical idea - the HandleScope::Close(Handle
So there is our previous code scope.Close(String::New("world"));.
String::New
This String class corresponds to the native string class in Node.js. Inherited from Value class. Similar to this, there is also:
•Array
•Integer
•Boolean
•Object
•Date
•Number
•Function
•...
Some of these things are inherited from Value, and some are inherited twice. We won’t do much research here. You can look at the V8 code (at least the header files) or read this manual.
And what about this New? You can see it here. Just create a new String object.
At this point, we have completed the analysis of this main function.
Export object
Let’s review it. If we write it in Node.js, how do we export functions or objects?
So, how do we do this in C?
Initialization function
First, we write an initialization function:
This is a turtle butt! It doesn’t matter what the function name is, but the parameter passed in must be a Handle
Then, we write the exported stuff here:
The general meaning is that, add a field called hello to this exports object, and the corresponding thing is a function, and this function is our dear Hello function.
To put it plainly in pseudo code:
Done!
(It’s done, sister! Shut up (‘д‘⊂彡☆))Д´)
True·Export
This is the last step. We finally have to declare that this is the entrance to the export, so we add this line at the end of the code:
NODE_MODULE(hello, init)
Did you pay a nenny? ! What is this?
Don’t worry, this NODE_MODULE is a macro, which means that we use the init initialization function to export the things to be exported to hello. So where does this hello come from?
It comes from the file name! Yes, that's right, it comes from the file name. You don't need to declare it in advance, and you don't have to worry about not being able to use it. In short, whatever the name of your final compiled binary file is, fill in the hello here, except for the suffix of course.
See the official documentation for details.
Note that all Node addons must export an initialization function:
There is no semi-colon after NODE_MODULE as it's not a function (see node.h).
The module_name needs to match the filename of the final binary (minus the .node suffix).
Compile (๑•́ ₃ •̀๑)
Come on, let’s compile it together!
Let’s create a new archive file similar to Makefile - binding.gyp.
And add this code inside:
Why do you write it like this? You can refer to the official documentation of node-gyp.
configure
After the file is ready, we need to execute this command in this directory:
If everything is normal, a build directory should be generated, and there will be related files in it, maybe M$ Visual Studio's vcxproj file, etc., maybe Makefile, depending on the platform.
build
After the Makefile is generated, we start constructing and compiling:
$ node-gyp build
When everything is compiled, it is truly done! If you don’t believe me, take a look at the build/Release directory. Is there a hello.node file below? Yes, this is the soap that C will pick up for Node.js later!
Get gay! Node ヽ(✿゚▽゚)ノ C
We create a new file jianfeizao.js in the directory just now:
Did you see it? Did you see it? It's out! It's out! The result of Node.js and C being radical! This addon.hello() is the Handle
Go to sleep, the next section will be more in-depth
It’s getting late, so I’ll finish writing here today. By now, everyone can create the most basic C extension of Hello world. The next time I write it should be more in-depth. As for when the next time will be, I actually don’t know.
(Hey, hey, hey, how can a masturbator be so irresponsible! (o゚ロ゚)┌┛Σ(ノ´ω`)ノ