Aunue tengamos tiempo y experiencia programando en JS, existen ocasiones en que el rendimiento de JavaScriptJavaScript es un lenguaje de programaci贸n que funciona en el lado del cliente y con el que las webs pueden ser m谩s funcionales. Incorporaci贸n en c贸digo HTML El c贸digo JavaScript puede ser incrustado en las p谩ginas HTML, para que adquieran funcionalidad. Existen varias opciones. Puede estar entre las etiquetas <SCRIPT> y </SCRIPT>, puede estar contenido en un archivo externo, puede ser un par谩metro de las etiquetas HTML, y puede estar plus no es suficiente, por lo que se debe depender m谩s de los m贸dulos nativos de Node.js. Sigue leyendo para que te enteres c贸mo hacer esto.

While native extensions are definitely not a beginner's topic, I would recommend this article to all Node.js developers to gain a little insight into how they work.

Common use cases for native Node.js modules

Knowledge of native modules is useful when you are adding a native extension as a dependency, which you could have already done!

Just do a little look at the list of some popular modules that use native extensions. You are using at least one of them, or am I wrong?

  • httpsHTTPS (protocolo de Transferencia de Hiper-Texto) es un protocolo que permite determinar una conexi贸n segura entre el servidor y el cliente, que no puede ser interceptada por personas no autorizadas. En resumidas cuentas, es la versi贸n segura de el http (Hyper Text Transfer Protocol) C贸mo funciona Una conexi贸n HTTP est谩ndar en Internet puede ser f谩cilmente secuestrada por partes no autorizadas. El prop贸sito de una conexi贸n HTTPS es evitar esto: encriptar plus://github.com/wadey/node-microtime
  • https://github.com/node-inspector
  • https://github.com/node-inspector/v8-profiler
  • httpEl HTTP (Hyper Text Transfer Protocol) es un protocolo que se usa para transmitir datos en redes. HTTP es un est谩ndar t茅cnico generalmente aceptado que establece c贸mo un cliente web se comunica con un servidor para que los datos solicitados por el cliente puedan ser cargados y mostrados. Informaci贸n general Junto con el URL y el HTML, HTTP es uno de los conceptos m谩s importantes de Internet (www). Fue desarrollado plus://www.nodegit.org/

There are a few reasons why one might consider module creation Node.js native speakers, including but not limited to:

  • Performance Critical Applications: Let's be honest, Node.js is great for performing asynchronous input and output operations, but when it comes to true number computation, it's not such a good choice.
  • Conexi贸n a las APIConcepto de API驴Qu茅 es una API?Una API, siglas de Application Programming Interface o Interfaz de Programaci贸n de Apps, es un recopilatorio de c贸digo que se puede emplear para que varias apps se comuniquen entre ellas. Es algo que realiza una tarea equivalente a la interfaz de usuario al momento de promover la interacci贸n entre persona y programa, solo que aplicado 煤nica y exclusivamente dentro del entorno del software.A煤n cuando suene plus de nivel inferior, por ejemplo: sistema operativo.
  • Bridging the C or C ++ Libraries and Node.js

What are the native modules?

Node.js plugins are dynamically linked shared objects written in C or C ++, which can be loaded into Node.js using the function require (), and are used as if they were an ordinary Node.js module.

This means that (if done correctly) the quirks of C / C ++ can be hidden from the module consumer. What you will see instead is that your module is a Node.js module, as if there were

Node.js runs on the V8 JavaScript engine, which is a C program on its own. We can write code that interacts directly with this C program in your own language, which is great because we can avoid a lot of expensive serialization and communication costs.

Adem谩s, en una entrada de BlogEl t茅rmino blog se usa para describir un diario virtual en Internet. El autor de un blogger puede publicar posts sobre cualquier tema. Los posts suelen estar presente de forma cronol贸gica. El estilo de redacci贸n de un blog suele ser informal y se escribe en primera persona. No obstante, adem谩s son posibles otros estilos, por ejemplo en el caso de los peri贸dicos online, en los que la atenci贸n se centra plus anterior que hemos aprendido sobre el costo del colector de basura Node.js. Aunque la recolecci贸n de basura se puede evitar por completo si decides administrar la memoria tu mismo (porque C y C ++ no tiene un concepto de GC), crear谩 problemas de memoria mucho m谩s f谩cilmente.

Writing native extensions requires knowledge of one or more of the following topics:

  • Libuv
  • V8
  • Node.js internals

They all have excellent documentation. If you are entering this field, I recommend you read them.

Sin m谩s pre谩mbulos, vamos a comenzar con el tema fuerte de este postConcepto de Post驴Qu茅 es un Post?Un Post es todo aquel contenido, sea post, opini贸n, noticia u otro g茅nero, que un autor publica en un blog. Este puede ser de car谩cter corporativo o meramente ocioso; pero siempre tiene como meta arrojar informaci贸n o reflejar una idea, al mismo tiempo de facilitar que los usuarios encuentren la web donde se recoge por medio de de buscadores y dem谩s plataformas online.Generalmente, se han plus:

Prerequisites

  • For Linux operating system:
    1. Use python (I recommend using v2.7, since v3.xx is not supported)
    2. Make.
    3. Use a suitable C or C ++ compilation toolchain, such as GCC
  • For Mac operating system:
    1. Have Xcode installed: make sure you not only install it, but start it at least once and accept its terms and conditions; otherwise it won't work!
  • For Windows operating system:
    1. Run cmd.exe as administrator and enter the command npm install --global --production windows-build-tools, which will install everything for you.
    2. Another option is to install Visual Studio: (it has all the C / C ++ build tools preconfigured)
    3. Or use the Linux subsystem provided by the latest Windows build. With that, follow the LINUX instructions above.

Creating our native Node.js extension

We are going to create our first file for the native extension. We can use the extension聽.DC which means it's C with classes, or the extension聽.cpp which is the default for C ++. The Google Style Guide recommends .DC, so for this tutorial I'll stick with it.

At this point we are going to see the complete file and then explain it line by line.

#include const int maxValue = 10; int numberOfCalls = 0; void WhoAmI (const v8 :: FunctionCallbackInfo & args) {v8 :: Isolate * isolate = args.GetIsolate (); auto message = v8 :: String :: NewFromUtf8 (isolate, "I am Node Hero!"); args.GetReturnValue (). Set (message); } void Increment (const v8 :: FunctionCallbackInfo & args) {v8 :: Isolate * isolate = args.GetIsolate (); if (! args [0] -> IsNumber ()) {isolate-> ThrowException (v8 :: Exception :: TypeError (v8 :: String :: NewFromUtf8 (isolate, "The argument must be a number"))); return; } double argsValue = args [0] -> NumberValue (); if (numberOfCalls + argsValue> maxValue) {isolate-> ThrowException (v8 :: Exception :: Error (v8 :: String :: NewFromUtf8 (isolate, "The counter went through the roof!"))); return; } numberOfCalls + = argsValue; auto currentNumberOfCalls = v8 :: Number :: New (isolate, static_cast (numberOfCalls)); args.GetReturnValue (). Set (currentNumberOfCalls); } void Initialize (v8 :: Local exports) {NODE_SET_METHOD (exports, "whoami", WhoAmI); NODE_SET_METHOD (exports, "increment", Increment); } NODE_MODULE (module_name, Initialize)

Now we are going to see the file line by line

#include

The include in C ++ it's like require ()in JavaScript. It will extract everything from the given file, but instead of linking it directly to the source, in C ++ we have the concept of header files.

Podemos declarar la interfaz exacta en los archivos de encabezado sin implementaci贸n y luego podemos incluir las implementaciones por su archivo de encabezado. El enlazador C ++ se encargar谩 de vincular estos dos juntos. Piensa en ello como un archivo de documentaci贸n que describe tu contentsEl contenido puede ser muy dif铆cil de definir con precisi贸n. Es una definici贸n que se refiere a las declaraciones contenidas en un documento o publicaci贸n de cualquier tipo y puede incluir las tecnolog铆as de la informaci贸n y la comunicaci贸n. Esto cubre todos los tipos de medios como im谩genes y texto. A parte de esto, en el campo de la optimizaci贸n de motores de b煤squeda, los t茅rminos duplicar contenido, contenido 煤nico, plus, que puede ser reutilizado desde su c贸digo.

void WhoAmI(const v8::FunctionCallbackInfo<v8::value>&amp; args) { v8::Isolate* isolate = args. GetIsolate(); auto message = v8::String::NewFromUtf8(isolate, &quot;I am Node Hero!&quot;); args. GetReturnValue(). Set(message); } [php] Because this will be a native extension, the v8 namespace is available for use. Note the notation <strong>v8 ::</strong>, which is used to access the v8 interface. If you do not want to include <strong>v8 ::</strong> Before using any of the types provided by v8, you can add it using <strong>using</strong> <strong>v8;</strong> to the top of the file. You can then omit all the specifiers <strong>v8 ::</strong> namespace their types, but this can introduce name collisions into your code, so be careful when using them. To be 100% clear, I&#039;ll use the notation <strong>v8 ::</strong> for all v8 types in the code shown. In our example code, we have access to the arguments with which the function was called (from JavaScript), via the object <strong>args</strong> which also provides us with all the information related to the call. With <strong>v8::Isolate*</strong> we are getting access to the current JavaScript scope for our function. Scopes work just like in JavaScript: we can assign variables and bind them to the lifetime of that specific code. We don&#039;t have to worry about de-allocating these chunks of memory, because we allocate them just like we would in JavaScript, and the garbage collector will take care of them automatically. [php] function () { var a = 1; } // scope

Via args.GetReturnValue ()聽we access the return value of our function. We can configure it for whatever we want as long as it is from space v8 :: of names.

C ++ has built-in types for storing integers and strings, but JavaScript only understands its own v8 :: object types. As long as we are in the realm of the C ++ world, we can use the ones that are built into C ++, but when dealing with JavaScript objects and interoperability with JavaScript code, we have to transform the C ++ types into other than they understand each other. by the JavaScript context. These are the types that are exposed in v8 :: namespace as v8 :: Stringo v8 :: Object.

void WhoAmI (const v8 :: FunctionCallbackInfo & args) {v8 :: Isolate * isolate = args.GetIsolate (); auto message = v8 :: String :: NewFromUtf8 (isolate, "I am Node Hero!"); args.GetReturnValue (). Set (message); }

Let's look at the second method in our file that increments a counter by a supplied argument to an upper bound of 10.

This function also accepts a JavaScript parameter. When you are accepting JavaScript parameters, you have to be careful because they are loosely written objects. (You are probably used to this in JavaScript by now.)

Array array contains v8 :: Objects, por lo que son todos objetos de JavaScript, pero ten cuidado con estos, porque en este contexto nunca podemos estar seguros de lo que pueden contener. Tenemos que verificar expl铆citamente los tipos de estos objetos. Afortunadamente, hay m茅todos auxiliares que se agregan a estas clases para determinar su tipo antes de la conversionConversi贸n es una acci贸n precisa que lleva a cabo un usuario al visitar un portal web. Algunas formas cl谩sica de conversi贸n son, por ejemplo, una compra, una descarga o una suscripci贸n a la newsletter. Un parte del SEO o del Marketing Online es la Optimizaci贸n de Ratio de Conversi贸n (CRO). En el Marketing de afiliaci贸n se usa para la conversi贸n de los editores. Informaci贸n general Hay diferentes indicadores para medir plus de tipos.

To maintain compatibility with existing JavaScript code, we should throw an error if the type of arguments is wrong. To throw a type error, we have to create an error object with the constructor
v8 :: Exception :: TypeError (). The next block will launch a TypeError if the first argument is not a number.

if (! args [0] -> IsNumber ()) {isolate-> ThrowException (v8 :: Exception :: TypeError (v8 :: String :: NewFromUtf8 (isolate, "The argument must be a number"))); return; }

In JavaScript that snippet would look like:

If (typeof arguments [0]! == 'number') {throw new TypeError ('The argument must be a number')}