1. napi_status napi_create_function(napi_env env,
    2. const char* utf8name,
    3. size_t length,
    4. napi_callback cb,
    5. void* data,
    6. napi_value* result);
    • [in] env: The environment that the API is invoked under.
    • [in] utf8Name: The name of the function encoded as UTF8. This is visible within JavaScript as the new function object’s name property.
    • [in] length: The length of the utf8name in bytes, or NAPI_AUTO_LENGTH if it is null-terminated.
    • [in] cb: The native function which should be called when this function object is invoked. [napi_callback][] provides more details.
    • [in] data: User-provided data context. This will be passed back into the function when invoked later.
    • [out] result: napi_value representing the JavaScript function object for the newly created function.

    Returns napi_ok if the API succeeded.

    This API allows an add-on author to create a function object in native code. This is the primary mechanism to allow calling into the add-on’s native code from JavaScript.

    The newly created function is not automatically visible from script after this call. Instead, a property must be explicitly set on any object that is visible to JavaScript, in order for the function to be accessible from script.

    In order to expose a function as part of the add-on’s module exports, set the newly created function on the exports object. A sample module might look as follows:

    1. napi_value SayHello(napi_env env, napi_callback_info info) {
    2. printf("Hello\n");
    3. return NULL;
    4. }
    5. napi_value Init(napi_env env, napi_value exports) {
    6. napi_status status;
    7. napi_value fn;
    8. status = napi_create_function(env, NULL, 0, SayHello, NULL, &fn);
    9. if (status != napi_ok) return NULL;
    10. status = napi_set_named_property(env, exports, "sayHello", fn);
    11. if (status != napi_ok) return NULL;
    12. return exports;
    13. }
    14. NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)

    Given the above code, the add-on can be used from JavaScript as follows:

    1. const myaddon = require('./addon');
    2. myaddon.sayHello();

    The string passed to require() is the name of the target in binding.gyp responsible for creating the .node file.

    Any non-NULL data which is passed to this API via the data parameter can be associated with the resulting JavaScript function (which is returned in the result parameter) and freed whenever the function is garbage-collected by passing both the JavaScript function and the data to [napi_add_finalizer][].

    JavaScript Functions are described in [Section 19.2][] of the ECMAScript Language Specification.