Home Web Front-end JS Tutorial Three ways to implement components in Node.js_node.js

Three ways to implement components in Node.js_node.js

May 16, 2016 pm 03:13 PM

First introduce the difference between using v8 API and using swig framework:

(1) The v8 API method is the native method provided by the official, with powerful and complete functions. The disadvantage is that you need to be familiar with the v8 API, which is more troublesome to write. It is strongly related to js and cannot easily support other scripting languages.

(2) swig is a third-party support, a powerful component development tool that supports generating C++ component packaging code for a variety of common scripting languages ​​such as python, lua, js, etc. swig users only need to write C++ code and swig configuration files You can develop C++ components in various scripting languages ​​without knowing the component development frameworks of various scripting languages. The disadvantage is that it does not support JavaScript callbacks, the documentation and demo code are incomplete, and there are not many users.

1. Pure JS to implement Node.js components
(1) Go to the helloworld directory and execute npm init to initialize package.json. Ignore the various options and leave them as defaults.

(2) Component implementation index.js, for example:

module.exports.Hello = function(name) {
    console.log('Hello ' + name);
}
Copy after login

(3) Execute in the outer directory: npm install ./helloworld, helloworld is then installed in the node_modules directory.
(4) Write component usage code:

var m = require('helloworld');
m.Hello('zhangsan');
//输出: Hello zhangsan
Copy after login

2. Use v8 API to implement JS components - synchronous mode
(1) Write binding.gyp, eg:

{
 "targets": [
  {
   "target_name": "hello",
   "sources": [ "hello.cpp" ]
  }
 ]
}
Copy after login

(2) Write the implementation of the component hello.cpp, eg:

#include <node.h>

namespace cpphello {
  using v8::FunctionCallbackInfo;
  using v8::Isolate;
  using v8::Local;
  using v8::Object;
  using v8::String;
  using v8::Value;

  void Foo(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();
    args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Hello World"));
  }

  void Init(Local<Object> exports) {
    NODE_SET_METHOD(exports, "foo", Foo);
  }

  NODE_MODULE(cpphello, Init)
}

Copy after login

(3) Compile component

node-gyp configure
node-gyp build
./build/Release/目录下会生成hello.node模块。
Copy after login

(4) Write test js code

const m = require('./build/Release/hello')
console.log(m.foo()); //输出 Hello World
Copy after login

(5) Add package.json for installation eg:

{                                                                                                         
  "name": "hello",
  "version": "1.0.0",
  "description": "", 
  "main": "index.js",
  "scripts": {
    "test": "node test.js"
  }, 
  "author": "", 
  "license": "ISC"
}
Copy after login

(5) Install components to node_modules

Go to the superior directory of the component directory and execute: npm install ./helloc //Note: helloc is the component directory
The hello module will be installed in the node_modules directory in the current directory. The test code is written like this:

var m = require('hello');
console.log(m.foo());  
Copy after login

3. Use v8 API to implement JS components - asynchronous mode
The above description is a synchronous component. foo() is a synchronous function, that is, the caller of the foo() function needs to wait for the foo() function to finish executing before proceeding. When the foo() function is an IO time-consuming operation, function, the asynchronous foo() function can reduce blocking waits and improve overall performance.

To implement asynchronous components, you only need to pay attention to the uv_queue_work API of libuv. When implementing the component, except for the main code hello.cpp and the component user code, other parts are consistent with the above three demos.

hello.cpp:

/*
* Node.js cpp Addons demo: async call and call back.
* gcc 4.8.2
* author:cswuyg
* Date:2016.02.22
* */
#include <iostream>
#include <node.h>
#include <uv.h> 
#include <sstream>
#include <unistd.h>
#include <pthread.h>

namespace cpphello {
  using v8::FunctionCallbackInfo;
  using v8::Function;
  using v8::Isolate;
  using v8::Local;
  using v8::Object;
  using v8::Value;
  using v8::Exception;
  using v8::Persistent;
  using v8::HandleScope;
  using v8::Integer;
  using v8::String;

  // async task
  struct MyTask{
    uv_work_t work;
    int a{0};
    int b{0};
    int output{0};
    unsigned long long work_tid{0};
    unsigned long long main_tid{0};
    Persistent<Function> callback;
  };

  // async function
  void query_async(uv_work_t* work) {
    MyTask* task = (MyTask*)work->data;
    task->output = task->a + task->b;
    task->work_tid = pthread_self();
    usleep(1000 * 1000 * 1); // 1 second
  }

  // async complete callback
  void query_finish(uv_work_t* work, int status) {
    Isolate* isolate = Isolate::GetCurrent();
    HandleScope handle_scope(isolate);
    MyTask* task = (MyTask*)work->data;
    const unsigned int argc = 3;
    std::stringstream stream;
    stream << task->main_tid;
    std::string main_tid_s{stream.str()};
    stream.str("");
    stream << task->work_tid;
    std::string work_tid_s{stream.str()};
    
    Local<Value> argv[argc] = {
      Integer::New(isolate, task->output), 
      String::NewFromUtf8(isolate, main_tid_s.c_str()),
      String::NewFromUtf8(isolate, work_tid_s.c_str())
    };
    Local<Function>::New(isolate, task->callback)->Call(isolate->GetCurrentContext()->Global(), argc, argv);
    task->callback.Reset();
    delete task;
  }

  // async main
  void async_foo(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();
    HandleScope handle_scope(isolate);
    if (args.Length() != 3) {
      isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "arguments num : 3")));
      return;
    } 
    if (!args[0]->IsNumber() || !args[1]->IsNumber() || !args[2]->IsFunction()) {
      isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "arguments error")));
      return;
    }
    MyTask* my_task = new MyTask;
    my_task->a = args[0]->ToInteger()->Value();
    my_task->b = args[1]->ToInteger()->Value();
    my_task->callback.Reset(isolate, Local<Function>::Cast(args[2]));
    my_task->work.data = my_task;
    my_task->main_tid = pthread_self();
    uv_loop_t *loop = uv_default_loop();
    uv_queue_work(loop, &my_task->work, query_async, query_finish); 
  }

  void Init(Local<Object> exports) {
    NODE_SET_METHOD(exports, "foo", async_foo);
  }

  NODE_MODULE(cpphello, Init)
}

Copy after login

The idea of ​​asynchronous is very simple. To implement a work function, a completion function, and a structure that carries data for cross-thread transmission, just call uv_queue_work. The difficulty is familiarity with v8 data structure and API.

test.js

// test helloUV module
'use strict';
const m = require('helloUV')

m.foo(1, 2, (a, b, c)=>{
  console.log('finish job:' + a);
  console.log('main thread:' + b);
  console.log('work thread:' + c);
});
/*
output:
finish job:3
main thread:139660941432640
work thread:139660876334848
*/

Copy after login

4. swig-javascript implements Node.js components
Use swig framework to write Node.js components

(1) Write the implementation of the component: *.h and *.cpp

eg:

namespace a {
  class A{
  public:
    int add(int a, int y);
  };
  int add(int x, int y);
}
Copy after login

(2) Write *.i, used to generate swig packaging cpp file
eg:

/* File : IExport.i */
%module my_mod 
%include "typemaps.i"
%include "std_string.i"
%include "std_vector.i"
%{
#include "export.h"
%}
 
%apply int *OUTPUT { int *result, int* xx};
%apply std::string *OUTPUT { std::string* result, std::string* yy };
%apply std::string &OUTPUT { std::string& result };                                                                                
 
%include "export.h"
namespace std {
  %template(vectori) vector<int>;
  %template(vectorstr) vector<std::string>;
};
Copy after login

The %apply above means that int* result, int* xx, std::string* result, std::string* yy, std::string& result in the code are output descriptions. This is a typemap, which is a replacement. .
If the pointer parameters in the C++ function parameters return a value (specified through OUTPUT in the *.i file), Swig will process them as the return value of the JS function. If there are multiple pointers, the return value of the JS function is list.
%template(vectori) vector means that a type vectori is defined for JS. This is usually a C++ function that uses vector as a parameter or return value. You need to use it when writing js code.
(3) Write binding.gyp for compilation using node-gyp
(4) Generate warpper cpp file. Pay attention to the v8 version information when generating, eg: swig -javascript -node -c++ -DV8_VERSION=0x040599 example.i
(5) Compile & test
The difficulty lies in the use of stl types and custom types. There are too few official documents in this regard.
swig - JavaScript encapsulation use of std::vector, std::string, see: My exercise, mainly focusing on the implementation of *.i files.
5. Others
When using v8 API to implement Node.js components, you can find similarities with implementing Lua components. Lua has a state machine and Node has Isolate.

When Node implements object export, it needs to implement a constructor, add a "member function" to it, and finally export the constructor as a class name. When Lua implements object export, it also needs to implement a factory function to create objects, and also needs to add "member functions" to the table. Finally, export the factory function.

Node’s js script has the new keyword, but Lua does not, so Lua only provides external object factories for creating objects, while Node can provide object factories or class encapsulation.

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

See all articles