nw.js上でNative Addonを動かす

公開:2015-04-16 05:59
更新:2020-02-15 04:37
カテゴリ:nw.js,native addon,javascript,nw.jsでデスクトップアプリを作る

io.jsでの不思議な挙動はとりあえずさておくことにした。よくよく考えると私はnw.js用のNative Addonを作りたいのだ。

試しに今まで作ったサンプルをnw.js 0.12.1で動かしてみることにした。nw.jsではnode-gypではなくnw-gypを使う。おそらくアドオンにくっつけるライブラリが違うだけでそのほかはおそらくnode-gypと同じだろう。

必要なライブラリのインストール

nw-gypとnanをインストールする。

npm install nw-gyp -g
npm install nan -S

binding.gypを書く

binding.gypファイルは下記の通り。

{
    'targets': [
        {
            "target_name" : "np",
            "sources" : [ "notepad.cpp" ],
            "include_dirs" : ["<!(node -e \"require('nan')\")"]
        },
    ],
}

notepad.cppファイルを書く

#include <node.h>
#include <nan.h>
#include <windows.h>

using namespace v8;

NAN_METHOD(open_notepad) {
    NanScope();

    ShellExecute(nullptr, "open", "notepad.exe", nullptr, nullptr, SW_SHOWNORMAL);
    NanReturnValue(NanUndefined());
}

void init(Handle&lt;Object&gt; exports) {
    exports->Set(NanSymbol("open"), NanNew<FunctionTemplate>(open_notepad)->GetFunction());
}

NODE_MODULE(np, init)

configureする

node-gyp configure target=0.12.1コマンドを実行し、ビルドのためのソリューションファイルを作る。

ビルドする

node-gyp buildでビルドする。そうするとbuild\Release\ディレクトリにnp.nodeファイルができる。これは拡張子は.nodeだが実態はDLLである。

package.jsonを作る

npm initコマンドでpackage.jsonを作る。startのところだけデフォルトにせず、index.htmlにする。あとはデフォルトのままでよいと思う。

index.htmlを作る

index.htmlファイルを作り、以下のHTMLファイルを書く。

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
  <h1>test page</h1>
  <script>
    var notepad = require('./build/Release/np.node');
    notepad.open();
  </script>
</body>
</html>

実行する

nw .で実行。動いた。

ソースコード

https://github.com/sfpgmr/gyptest

そういうわけで

動かしかたはわかったので引き続いてffmpegのライブラリとnw.jsを連携するコードをぼちぼち書いていくことにする。