Home > Article > Web Front-end > Use C/C to implement Node.js modules (2)_node.js
Reviewing the past and learning the new can make you happy
First of all, please remember this V8 online manual - http://izs.me/v8-docs/main.html.
Do you still remember the building.gyp file from last time?
Just like this, if you have a few more *.cc files, it will look like this:
"sources": [ "addon.cc", "myexample.cc" ]
Last time we separated the two steps. In fact, configuration and compilation can be put together:
$ node-gyp configure build
Have you finished reviewing? without? !
Okay, let’s continue.
Table of Contents
Function parameters
Now we finally have to talk about parameters.
Let us imagine that there is such a function add(a, b) which represents adding a and b and returning the result, so first write the function outline:
Handle
{
HandleScope scope;
//... Here we go again!
}
Arguments
This is the parameter of the function. Let’s take a look at v8’s official manual reference first.
•int Length() const
•Local
We don’t care about the rest, these two are important! One represents the number of parameters passed into the function, and the other bracket is used to access the nth parameter through the subscript index.
Therefore, we can roughly understand the above requirements as args.Length() is 2, args[0] represents a and args[1] represents b. And we need to determine that the type of these two numbers must be Number.
Notice that the index operator in square brackets returns a Local
•IsArray()
•IsBoolean()
•IsDate()
•IsFunction()
•IsInt32()
•IsNativeError()
•IsNull()
•IsNumber()
•IsRegExp()
•IsString()
•...
I won’t list them one by one, you can read the documentation for the rest. 。:.゚ヽ(*´∀`)ノ゚.:。
ThrowException
This is a function we will use later. Details can be found in the v8 documentation.
As the name suggests, it throws an error. After executing this statement, it is equivalent to executing a throw() statement in the Node.js local file. For example:
ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
It is equivalent to executing a Node.js:
throw new TypeError("Wrong number of arguments");
Undefined()
This function is also in the documentation.
Specifically, it is a null value, because some functions do not need to return any specific value, or there is no return value. At this time, Undefined() needs to be used instead.
Let’s do it, Saonian!
After understanding the above points, I believe you will be able to write the logic of a b soon. I will copy the code from the Node.js official manual and give it to you to go through:
Handle
{
HandleScope scope;
// means that more than 2 parameters can be passed in, but in fact we only use the first two
If(args.Length() < 2)
{
// throw error
ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
// Return null value
return scope.Close(Undefined());
}
If(!args[0]->IsNumber() || !args[1]->IsNumber())
{
// Throw an error and return null value
ThrowException(Exception::TypeError(String::New("Wrong arguments")));
return scope.Close(Undefined());
}
//
http://izs.me/v8-docs/classv8_1_1Value.html#a6eac2b07dced58f1761bbfd53bf0e366)
// `NumberValue` function
Local
}
Finally, write the export function at the end and it’s OK.
Callback function
In the last chapter, we only talked about Hello world. In this chapter, grandma made a conscious discovery and wrote another callback function.
As usual, we write the framework first:
{
HandleScope scope;
return scope.Close(Undefined());
}
func(function(msg) {
console.log(msg);
});
That is, it will pass in a parameter to the callback function. We imagine it is a string, and then we can console.log() it out.
First you need to have a string series
Without further ado, let’s feed it a string first and then talk about it. (√ ζ ε:)
But we have to make this string a universal type, because Node.js code is weakly typed.
Local
What? You ask me what is Local
Then let me talk about it a little bit, refer to it here and the V8 reference document.
As shown in the documentation, Local
Then let’s talk about Local.
There are two types of Handle, Local Handle and Persistent Handle. The types are Local
Then you need to have a parameter table series
How to get the command line parameters after calling C/C from the terminal command line?
void main(int argc, char* argv[])
{
// ...
}
By the way, argc here is the number of command line parameters, and argv[] is each parameter. Then calling the callback function of Node.js, v8 also adopts a similar method:
~~QAQ is stuck in Handle
After I verified it in many aspects (SegmentFault, StackOverflow and a KouKou group), I finally solved the meaning of the three parameters of the above function.
I won’t say much about the next two parameters. One is the number of parameters, and the other is an array of parameters. As for the first parameter Handle
It is the same as apply in JS. In JS, you do
The object passed as the first argument becomes this within the function scope. More documentation on MDN. If you don't know JS well, you can read more about JS's this here: http://unschooled.org /2012/03/understanding-javascript-this/
——Excerpted from StackOverflow
In short, its function is to specify the this pointer of the called function. The usage of this Call is similar to bind(), call(), and apply() in JavaScript.
So what we have to do is to build the parameter table first, and then pass in the Call function for execution.
The first step is to display the conversion function, because it is originally an Object type:
Local
The second step is to create a parameter table (array):
Local
Last call function series
Call cb and pass the parameters in:
cb->Call(Context::GetCurrent()->Global(), 1, argv);
The first parameter here, Context::GetCurrent()->Global(), means getting the global context as this of the function; the second parameter is the number in the parameter table (after all, although Node.js The array has a length attribute, but the system actually does not know the length of the array in C, and you have to pass in a number yourself to indicate the length of the array); the last parameter is the parameter table we just created.
Final Chapter Final Document Series
I believe everyone is already familiar with this step, which is to write the function, then put it into the exported function, and finally declare it.
I will just release the code directly, or you can go directly to the Node.js documentation.
Handle
{
HandleScope scope;
Local
const unsigned argc = 1;
Local
cb->Call(Context::GetCurrent()->Global(), argc, argv);
return scope.Close(Undefined());
}
void Init(Handle
NODE_MODULE(addon, Init)
Well done! Just do the last remaining steps yourself. As for calling this function in JS, I have mentioned it before.
Extra
Well, I feel like my study notes are becoming more and more unrestrained. Please break it down~
Let’s stop here today. In the process of writing study notes, I got into trouble again, such as the meaning of the parameters of the Call function.
If you think this series of study notes is still helpful to you, come and join me in the fun~Σ>―(〃°ω°〃)♡→