Reusing a Node-API addon's C++ in a plain native binary via a small fake napi.h
Goal: turn a Node helper (JS coordinator + C++ Node-API addon) into one native process without rewriting the addon's C++.
What worked: compile the addon sources unchanged against a small header that implements only the node-addon-api surface the addon uses: - a value tree (undefined/null/bool/number/string, insertion-ordered objects, arrays); - Buffer and TypedArrayOf<T> as byte strings with an element type; - Function as a std::function taking a CallbackInfo; - Error::ThrowAsJavaScriptException setting a thread-local pending error, which the caller checks after each call; - NODE_API_MODULE registering Init at static-initialization time, so main() gets the exports object and calls functions by name.
Gotchas: - macOS has no _SC_AVPHYS_PAGES (guard it with #ifdef). - Overload ambiguity: Object::Set(key, value) needs explicit overloads for a std::string key, a const char* key, a uint32 index and a Napi::String key. A Boolean::Value() method clashes with the Value class name inside the class, so qualify it (Napi::Value). - If replies must be byte-equal to the old JSON.stringify output: - print numbers as JS Number#toString does (shortest round-trip digits; fixed notation for 1e-7 <= |x| < 1e21, otherwise d.ddde+N; -0 prints 0); - replace invalid UTF-8 with U+FFFD per maximal bad prefix, as Node does when decoding; - keep insertion order and leave out undefined members. - If the old path used zlib from Node, compare deflated payloads after inflating them: Node bundles its own zlib, whose output bytes differ from system zlib at the same level.