napajs/examples/modules/hello-world
Yulong Wang 864ddc7e35 Fix napajs example module (#118)
* Fix file extension for napa example module

* Fix test for example module 'async-number'
2017-11-06 17:22:53 -08:00
..
lib Formalize module development depending on 'napajs' (#38) 2017-08-16 18:44:52 -07:00
napa resolve napajs_inc/napajs_lib by build.paths (#57) 2017-08-30 10:43:20 -07:00
test resolve napajs_inc/napajs_lib by build.paths (#57) 2017-08-30 10:43:20 -07:00
.gitignore Formalize module development depending on 'napajs' (#38) 2017-08-16 18:44:52 -07:00
.npmignore Formalize module development depending on 'napajs' (#38) 2017-08-16 18:44:52 -07:00
README.md Merged PR 327505: Merge dev/dapeng/license to master 2017-07-19 00:29:19 +00:00
binding.gyp Fix napajs example module (#118) 2017-11-06 17:22:53 -08:00
package.json resolve napajs_inc/napajs_lib by build.paths (#57) 2017-08-30 10:43:20 -07:00

README.md

Hello World

This example shows the simple napa module, which shows the basic difference between node.js module and napa module.

#include <napa/module.h>

namespace napa {
namespace demo {

using namespace v8;

void Method(const FunctionCallbackInfo<Value>& args) {
    auto isolate = args.GetIsolate();
    args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}

void Init(Local<Object> exports) {
    NAPA_SET_METHOD(exports, "hello", Method);
}

NAPA_MODULE(addon, Init)

}  // namespace demo
}  // namespace napa

Transition from node.js module

  • napa/module.h is used instead of node.h. Depending on preprocessor definition, NAPA_MODULE_EXTENSION or BUILDING_NODE_EXTENSION preprocessor definition, napa/module.h includes necessary napa or node header files accordingly and build system creates either node.js module or napa module.
  • NAPA_SET_METHOD is equivalent to NODE_SET_METHOD. This module will have hello() function.
  • NAPA_MODULE is equivalent to NODE_MODULE, which exports an initialization function.

Typescript

It's recommended that typescript or typescript definition is provided to let the user know the APIs without the source codes and develop Typescript project easily.

hello-world.ts

var addon = require('../bin/addon');

export function hello(): string {
    return addon.hello();
}

hello-world.d.ts

export declare function hello(): string;

Mocha test

var assert = require('assert');
var helloWorld = require('hello-world');

describe('Test suite for hello-word', function() {
    it('prints the string "world"', function() {
        var result = helloWorld.hello();
        assert.equal(result, 'world');
    });
})