{"id":20439402,"url":"https://github.com/skitsanos/node-napi-cpp","last_synced_at":"2025-03-05T07:32:06.897Z","repository":{"id":153096235,"uuid":"399085968","full_name":"skitsanos/node-napi-cpp","owner":"skitsanos","description":"Example on how to use Node.js N-API in C++","archived":false,"fork":false,"pushed_at":"2024-03-05T07:54:36.000Z","size":24,"stargazers_count":2,"open_issues_count":1,"forks_count":0,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-01-15T20:19:54.989Z","etag":null,"topics":["cpp","napi","node-addon","node-addon-api","nodejs"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/skitsanos.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-08-23T11:57:16.000Z","updated_at":"2024-01-17T18:00:35.000Z","dependencies_parsed_at":"2024-03-05T08:58:45.114Z","dependency_job_id":null,"html_url":"https://github.com/skitsanos/node-napi-cpp","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/skitsanos%2Fnode-napi-cpp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/skitsanos%2Fnode-napi-cpp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/skitsanos%2Fnode-napi-cpp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/skitsanos%2Fnode-napi-cpp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/skitsanos","download_url":"https://codeload.github.com/skitsanos/node-napi-cpp/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241988259,"owners_count":20053623,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cpp","napi","node-addon","node-addon-api","nodejs"],"created_at":"2024-11-15T09:17:10.012Z","updated_at":"2025-03-05T07:32:06.825Z","avatar_url":"https://github.com/skitsanos.png","language":"C++","readme":"# node-napi-cpp\nExample on how to use Node.js N-API in C++\n\n### Dependencies\n\n- *node-cmake* - A CMake-based build system for Node.js native modules\n- *node-addon-api* - This module contains header-only C++ wrapper classes which simplify the use of the C based Node-API provided by Node.js when using C++. It provides a C++ object model and exception handling semantics with low overhead\n- *cmake-js* - CMake.js is a Node.js/io.js native addon build tool which works (almost) exactly like node-gyp, but instead of gyp, it is based on CMake build system.\n\nInstall dependencies before doing anything:\n\n```sh\nyarn add node-cmake node-addon-api cmake-js\n```\n\n### CMakeLists.txt\n\nTested on Node.js 12, 14 and 16, configuration made in a way that it usses `node-cmake` and `node-addon-api` bits installed earlier, so all your headers are in place and no additional configuration required. Well, just change your project name instead `demo` into something you like more at line #14.\n\n### Calling JS module from C++\n\n`DemoClass.cpp` demonstrates how to call `require` from C++. There is one thing about it that not really documented on Node.js references and manuals -- `require` is not a part of Node.js internals and available only at run time, so you can't call it directly in any way within your C++ add-on, but you can pass it to your add-on.\n\n```js\nconst addon = require('../build/Release/demo');\nconst demo = new addon.DemoClass(require);\n```\n\nSo let's say you have a JavaScript module `hi.js` that will be called in DemoClass:\n\n```js\nconst welcome = () =\u003e 'Welcome back!';\n\nmodule.exports = welcome;\n```\n\nIn DemoClass constructor we pass `require` and we keep it for the future use:\n\n```cpp\nDemoClass::DemoClass(const CallbackInfo \u0026args) : ObjectWrap(args) {\n    this-\u003e_env = args.Env();\n\n    if (args.Length() \u003c 1 || !args[0].IsFunction()) {\n        Napi::TypeError::New(this-\u003e_env, \"Function expected\").ThrowAsJavaScriptException();\n    }\n\n    //\n    // verify arguments passed to ensure that it was the {require} function that was sent as an ergument\n    //\n    Napi::Function require = args[0].As\u003cNapi::Function\u003e();\n\n    std::regex self_regex(\"^function require\\\\(path\\\\)\",\n                          std::regex_constants::ECMAScript | std::regex_constants::icase);\n\n    if (!std::regex_search(require.ToString().Utf8Value().c_str(), self_regex)) {\n        Napi::TypeError::New(this-\u003e_env, \"{require} Function expected\").ThrowAsJavaScriptException();\n    }\n\n    this-\u003e_require = Persistent(require);\n}\n```\n\nSince we know the `require` function signature we can check if it is the right one with a basic regular expression... Now we can build a method that will consume that `require`. So, literally, we tell C++ to perform `require('./hi')` that will return a fucntion and then call that function.\n\n\n```cpp\nNapi::String DemoClass::sayHi(const CallbackInfo \u0026args) {\n    Napi::Env env = args.Env();\n\n    std::vector\u003cnapi_value\u003e jsArgs = {String::New(env, \"./hi\")};\n\n    Napi::Function f = this-\u003e_require.Call(jsArgs).As\u003cFunction\u003e();\n    auto result = f.Call({}).As\u003cString\u003e().Utf8Value();\n\n    return Napi::String::New(this-\u003e_env, result);\n}\n```\n\nSo now, when we call this methods from Javascript:\n\n```js\nconsole.log(demo.sayHi());\n```\n\nIt will print out our 'Welcome back!' message\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fskitsanos%2Fnode-napi-cpp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fskitsanos%2Fnode-napi-cpp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fskitsanos%2Fnode-napi-cpp/lists"}