node.js] How to use native modules in NW.js | Using Sqlite3


I would like to leave a reminder that I struggled quite a bit with building native modules in NW.js.

With Electron, it was a one-touch process with the handy “electron-rebuild” module, but with NW.js, there was a bit of a curve.

Electron is the most famous native app framework, but I recently stopped using it. The reason is that it does not have a source code protection function. After all, it is bad from a security point of view to be able to see the code, and there is a possibility that the code will be cracked.

For now, let’s do a quick rebuild of the native module in NW.js.

development environment

  • Windows 11 Pro
  • node.JS v18.13.0
  • node-gyp v9.1.0
  • node-pre-gyp v0.17.0
  • nw v0.72.0
  • nw-gyp v3.6.6
  • sqlite3 v5.1.3

Native module rebuild

I recently had the opportunity to use Sqlite in my personal development of a native application and decided to adopt the “sqlite3” module. Since this is a native module, it needs to be rebuilt for use with NW.js.

-- プロジェクトのルート
|--- node_module
|~~~ src // ソース・ファイル
|=== build // 配布用ビルド済みパッケージ
|=== package.json

We are developing with the above structure. First, install the Sqlite3 module with npm.

npm i sqlite3 --save

Next, install the npm package required for the rebuild.

npm i node-gyp node-pre-gyp nw-gyp -g

It is recommended to install globally with the option “-g” for all.

On Windows, the command cannot be used without setting an environment variable, so please add “C:\Users[username]\AppData\Roaming\npm\node_modules” to your “PATH”.

Once the installation is complete, we will work on rebuilding the package “Sqlite3” that we have just installed. Unlike with Electron, you will need to move into the project of the module you wish to rebuild and do the work.

In other words, move to the installed “Sqlite3” project directory “プロジェクトルート\node_module\sqlite3” with the “cd” command and rebuild “sqlite3” with “node-pre-gyp” for NW.js.

cd .\mode_module\sqlite3
node-pre-gyp rebuild --runtime=node-webkit --target=0.72.0

As for the options used in node-pre-gyp, “–runtime=node-webkit” should remain the same, and “–target=x.x.x.x” should be the version number of the NW.js currently in use. For “–target_arch=x64”, please specify the architecture type of your PC.

This should allow for rebuilding.

I really wanted to use “nw-gyp” officially provided by NW.js directly, but at first the rebuild did not work because of an error message stating that “module_name” was not found.
However, the rebuild went through by running with the “–module_name” and “–module_path” options.
The “–module_name” and “–module_path” options are found in the “package.json” file directly under the sqlite3 project root.

cd .\mode_module\sqlite3
nw-gyp rebuild --module_path="./lib/binding/napi-v{napi_build_version}-{platform}-{libc}-{arch}" --module_name="node_sqlite3" --target=0.72.0 --target_arch=x64

Reference Site