Easy to get started Nodejs calls C + + (mixed programming with C + + and JS)

Source: Internet
Author: User
Tags install node npm install node


Because of the project, node. JS has recently been used to take a restful interface.
Performance is good, feel faster than spring boot and the like. And in addition to good performance, as long as the program structure is well organized, do not let too many callbacks to confuse the program structure, overall development efficiency is much faster than Java.

Using C + + to optimize some of the modules is a good choice if you want to improve efficiency further. In particular, Nodejs's support for mixed programming with C + + is good, and personal feeling is at the same level of ease of use as the extension module that writes Python.

We start with Hello World:
First, there is a blank working directory in which to build a node package management file Package.json, the content is:

{  "name": "test-cpp-module",  "version": "0.1.0",  "private": true,  "gypfile": true}

Then execute the command in the directory: npm install node-addon-api --save install the Development support package for the Nodejs extension module. This assumes that you have installed the Nodejs and the appropriate NPM package management tools, as well as the associated command-line compilation tools for Xcode. We do not repeat the installation configuration of these basic tools, please refer to the relevant official website documentation.
When the above command is complete, we have completed the configuration of the basic development environment.

The C + + module is described by the Binding.gyp file, and the related configuration of automatic compilation is done, and we create a new Binding.gyp file with the following contents:

  {"targets": [{"Target_name": "Democpp", "Sources": ["democpp.cc"      ], "include_dirs": ["<[email protected] (node-p \" require (' Node-addon-api '). Include\ ")"], "Dependencies": ["<! ( NODE-P \ "Require (' Node-addon-api '). Gyp\") "]," cflags! ": ["-fno-exceptions "]," cflags_cc! ": ["-fno-excepti    ONS "]," defines ": [" Napi_cpp_exceptions "]," xcode_settings ": {" gcc_enable_cpp_exceptions ":" Yes "} }  ]}
    • The file first uses Target_name to specify the name of the module after compilation.
    • Sources indicates that C + + source files, if there are multiple files, need to be separated by commas, placed in the same array.
    • Include_dirs is the header file introduction path used at compile time, which uses Node-p to execute the preset variables in the Node-addon-api module.
    • Dependencies is a must, do not change.
    • Later, the Cflags!/cflags_cc!/defines three line specifies that if the C + + program encounters an unexpected error, it is handled by the Napi interface, rather than by the C + + program itself. This prevents the C + + part of the program from accidentally exiting the program, but rather by the NODEJS program to capture the processing. If it is compiled and used in Linux, these three lines will suffice.
    • But if you're compiling on MacOS, you'll need the last xcode-settings setting, which is the same, which turns off the unintended handling of the MacOS compiler.
      Finally, C + + source code, democpp.cc file:
#include <napi.h>using namespace Napi;String Hello(const CallbackInfo& info) {  return String::New(info.Env(), "world");}Napi::Object  Init(Env env, Object exports) {  exports.Set("hello", Function::New(env, Hello));  return exports;}NODE_API_MODULE(addon, Init)

The introduction of napi.h header files in the program, the use of Napi namespace and the last Node_api_module (Addon,init) are templated, copied over without moving.
init function, use the exports.Set() function that introduces the call to be exposed to Nodejs. If there are multiple functions that need to be drawn out, write more than one line.
The Hello function is the part of our main demo, which is very simple, just to return a "hello" in string form.

When the above Democpp.cc/binding.gyp/package.json three files are ready, execute at the command line: npm install , if successful, you will get the output information like this:

$ npm install> [email protected] install /home/andrew/Documents/dev/html/nodejs/callcpp> node-gyp rebuild  SOLINK_MODULE(target) Release/nothing.node  CXX(target) Release/obj.target/democpp/democpp.o  SOLINK_MODULE(target) Release/democpp.node

This means that the compilation is completed successfully, and if it encounters an error, it can determine the solution based on the error message. Usually the environment configuration is missing related programs or the above three files have typographical errors.
Let's verify the compile result of the module, use Nodejs at the command line, introduce the compiled module file, and then call the Hello function to see:

Above is the simplest example, we add a bit of difficulty below. In the GNU environment, our programs usually contain many third-party extensions, and here's another example of calling OpenSSL:
Package.json files do not have to be modified, we do not need to add new dependency packages at the Nodejs level.
Compiling a C + + program with a third-party extension library typically requires specifying additional header file inclusion paths and linked third-party libraries at compile time, which are specified in Binding.gyp, which are parsed and applied to the command-line compilation tool when Nodejs is automatically compiled.

{  "targets": [    {      "target_name": "democpp",      "sources": [        "democpp.cc"      ],      "include_dirs": [        "<[email protected](node -p \"require(‘node-addon-api‘).include\")"      ],      "libraries": [         ‘-lssl -lcrypto‘,      ],      "dependencies": [        "<!(node -p \"require(‘node-addon-api‘).gyp\")"      ],      "cflags!": ["-fno-exceptions"],      "cflags_cc!": ["-fno-exceptions"],      "defines": ["NAPI_CPP_EXCEPTIONS"],      "xcode_settings": {        "GCC_ENABLE_CPP_EXCEPTIONS": "YES"      }    }  ]}

In MacOS and common Linux versions, OpenSSL's header files are automatically installed in the system's header file path, such as/usr/local/include, so the introduction path to the header file here does not increase. If you are using an extension library of your own installation, you need to add a new header file containing path in the Include_dirs section. The
then adds the Libraries section, which specifies the link parameters for the OpenSSL extension library -lssl-lcrypto , which is required. The
finally modifies the democpp.cc file and adds a function to encode the string MD5 using the MD5 algorithm in OpenSSL:

 #include <napi.h> #include <openssl/md5.h>using namespace napi;void openssl_md5 (const char *data, int Size, unsigned char *buf) {Md5_ctx C; Md5_init (&C); Md5_update (&c,data,size); Md5_final (buf,&c);} String GetMD5 (const callbackinfo& info) {env env = info. ENV (); std::string password = info[0]. As<string> (). Utf8value (); printf ("MD5 in str:%s%ld\n", Password.c_str (), password.size ()); unsigned char hash[16]; memset (hash,0,16); OPENSSL_MD5 (Password.c_str (), password.size (), hash); Char tmp[3]; Char md5str[33]={}; int i; for (i = 0; i < i++) {sprintf (tmp, "%02x", Hash[i]); strcat (MD5STR,TMP); } return String::new (env, md5str,32);} String Hello (const callbackinfo& info) {return string::new (info). ENV (), "World"); Napi::object Init (env env, Object Exports) {exports. Set ("Hello", function::new (env, hello)); Exports. Set ("MD5", Function::new (env, GetMD5)); return exports;} Node_api_module (addon, Init) 

For the convenience of work, the source code has added a OPENSSL_MD5 function, only for the internal use of the program. Because there is no derivation, Nodejs does not know the existence of this function.
A function that passes parameters to C + + from Nodejs is used info[0].As<String>().Utf8Value() in this form. The return value to Nodejs has been seen in the Hello function.
Each modification is completed and the same goes back to the command line using npm install recompile. To compile the process and information slightly, we look directly at the test call:

Want to verify the correctness of the calculations? You can perform the OpenSSL test directly:

$ echo -n "abc" | openssl md5900150983cd24fb0d6963f7d28e17f72

Well, no suspense the same.

Reference documents

Https://github.com/kriasoft/nodejs-api-starter
Https://github.com/nodejs/node-addon-api/blob/master/doc/node-gyp.md

Easy to get started Nodejs calls C + + (mixed programming with C + + and JS)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.