NW.JS (node-webkit) – An Introduction
Node webkit allows HTML5 applications to run in a desktop. It uses NodeJS and Chromium. Both are using the same V8 javscript engine. Since this runs as a desktop application, it doesn’t have the sandbox restrictions. So in the same page, you can open a file from file-system and then render the contents in the web browser.
NW.JS allows calling node js modules directly from DOM.
In this example, we would create a sample application which would read a JSON file from the file system and display its contents.
History of NW.JS
NW.JS was previously known as node-webkit. This was originally developed at Intel. This was open sourced at GitHub in 2011. NW.JS is GPU accelerated.
How is this possible?
How these two technologies work together when Chromium and Node JS has different message loops. Chromium’s message loop is based on MessagePump* family, while Node JS uses libUV for message loops. NW.JS implements MessagePumpForUV to bring Node JS’s libUV to Chromium message loop.
You would be required to download NW.JS package directly from github. I have downloaded here for Windows. The package needs to be unzipped. The contents are as follows:
First, Let’s say Hello to the World
Let’s first start with the Hello World example, to understand first how to run it simply. At the bare minimum, we need index.html and package.json files. Here are the contents of index.html; it just has a Hello World! text in the title and body.
Now comes the interesting bit; here are the contents of package.json. Generally, with package.json, we expect the details of npm packages for the app. But here we see some other details about the app itself. Since the app wouldn’t be running on a web browser directly; it has to run in nw.js window. Here we are providing some of the details about the window.
The window is not resizable; has no toolbars; and appears corresponding to the current mouse location. We have also provided the maximum and minimum dimensions for the window. The interesting part is what contents to display in the window?? That detail is provided by setting main; here we are using the contents of index.html.
In order to run this, we need to zip the folder containing the two files and change the extension from X.zip to X.nw. Now we can just drop the nw file to the nw.exe
And the app is shown as below:
Working With Files
Here we are reading the contents of GroceryItems.json using asyc readFile() provided from fs. After reading the contents of the file, it just logs it to the console.
Did you notice the dev tools? Yes DevTools are available for nw.js. We can enable that by setting the toolbars property of window to true as follows: