search
HomeWeb Front-endJS TutorialUse 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?

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

Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.