Home > Web Front-end > JS Tutorial > body text

Use C/C to implement Node.js modules (2)_node.js

WBOY
Release: 2016-05-16 16:35:31
Original
1106 people have browsed it

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?

Copy code The code is as follows:

{
"targets": [
{
"target_name": "addon",
"sources": [ "addon.cc" ]
}
]
}

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:

Copy code The code is as follows:

#include
using namespace v8;

Handle Add(const Arguments& args)
{
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 operator[](int i) const

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, which is the base class of all types in Node.js. Therefore, the parameters passed in are of uncertain type, and we must determine by ourselves what parameters they are. This is related to some functions of this Value type.

•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:

Copy code The code is as follows:

#include
using namespace v8;

Handle Add(const Arguments& args)
{
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 one of the first two parameters is not a number

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());
}

// Please refer to v8 documentation for details

//
http://izs.me/v8-docs/classv8_1_1Value.html#a6eac2b07dced58f1761bbfd53bf0e366) // `NumberValue` function
Local num = Number::New(args[0]->NumberValue() args[1]->NumberValue());

return scope.Close(num);

}

The function is done!

Finally, write the export function at the end and it’s OK.


Copy code The code is as follows:
void Init(Handle exports)
{
exports->Set(String::NewSymbol("add"),
FunctionTemplate::New(Add)->GetFunction());
}
NODE_MODULE(addon, Init)


After you compile it, we can use it like this:

Copy code The code is as follows:
var addon = require('./build/Release/addon') ;
console.log(addon.add(1, 1) "b");

You will see a 2b! ✧。٩(ˊᗜˋ)و✧*。

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:


Copy code The code is as follows:
#include
using namespace v8;
Handle RunCallback(const Arguments& args)

{
HandleScope scope;

// ... crackling crackling

return scope.Close(Undefined());

}

Then we decided that its usage is like this:

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::New(String::New("hello world"));

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 actually inherits from Handle. I remember that Handle was already mentioned in the previous chapter.

Then let’s talk about Local.


There are two types of Handle, Local Handle and Persistent Handle. The types are Local : Handle and Persistent : Handle respectively. There is no difference between the former and Handle. The life cycle is within the scope. The latter's life cycle is out of scope, and you need to manually call Persistent::Dispose to end its life cycle. In other words, Local Handle is equivalent to C `allocating objects on the stack and Persistent Handle is equivalent to C allocating objects on the heap.

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?

Copy code The code is as follows:

#include

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:

Copy code The code is as follows:
V8EXPORT Local v8::Function::Call(Handlerecv ,
int argc,
Handle argv[]
);

~~QAQ is stuck in Handle recv! ! ! Will continue writing tomorrow. ~~

Well, a new day has begun and I feel full of strength. (∩^o^)⊃━☆゚.*・。

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 recv, StackOverflow’s explanation is this:


It is the same as apply in JS. In JS, you do

Copy code The code is as follows:

var context = ...;
cb.apply(context, [ ...args...]);

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 cb = Local::Cast(args[0]);

The second step is to create a parameter table (array):
Local argv[argc] = { Local::New(String::New("hello world")) };

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.

Copy code The code is as follows:

#include
using namespace v8;

Handle RunCallback(const Arguments& args)
{
HandleScope scope;
Local cb = Local::Cast(args[0]);
const unsigned argc = 1;
Local argv[argc] = { Local::New(String::New("hello world")) };
cb->Call(Context::GetCurrent()->Global(), argc, argv);

return scope.Close(Undefined());
}

void Init(Handle exports, Handle module)
{
Module->Set(String::NewSymbol("exports"),
FunctionTemplate::New(RunCallback)->GetFunction());
}

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~Σ>―(〃°ω°〃)♡→

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template