Using Node and Electron to build Desktop Apps

From NSB App Studio
Jump to navigation Jump to search

Introduction

AppStudio now supports the use of a some of the biggest new technologies in the web development world.

Node.js is a runtime environment that executes JavaScript code outside the browser. That makes it suitable for writing server side software, which would normally be done in PHP or other languages. It works by having an executable stub which is able to call the V8 JavaScript engine, which powers Chrome.

npm is a repository of code which can be used with Node.js. It's included when you download Node. There is a huge number of packages available - over 750,000 at last count. You can include these packages in your Node project to add functionality. It might be for convenience: there are a lot of libraries which are much easier to include in your project than to write yourself. It might be for functionality: the modules can implement features which would not be available in the browser.

An example of a convenient library would be Lodash which adds hundreds of additional functions to JavaScript. A missing feature library would be fs-extra which allows full access to the file system.

Electron is framework which allows for the development of desktop GUI applications. Since it's built on Node.js, it already has the ability to run JavaScript code. It also uses Chrome's browser engine to render the UI using regular HTML. Each Electron app includes the V8 Runtime as well as the Chrome browser. Slack, Github Desktop and WhatsApp are examples of apps built using Electron.

Tutorial: Make an Electron app

AppStudio allows you to make normal AppStudio apps (programmed in Javascript or BASIC) into full blown Electron apps. You can distribute these apps as full blown executables, able to run on Windows, MacOS and Linux.

In this tutorial, we're going to use a module from npm called weather-js to create an app which gets weather data from weather.service.msn.com. It's very convenient: we don't have to figure out the MSN API to use it.

You will have to know how to use the command line (Terminal on MacOS, cmd or Powershell on Windows) and have AppStudio 7.2.3 or later installed.

Set up the project

1. Download and install Node. (This also installs npm.)

https://nodejs.org/en/download/

2. Using AppStudio, create a new project called ElectronWeather and save it.

3. Open a command line window in the newly created ElectronWeather.appstudio folder and type npm init. This creates a file named package.json, which has configuration info for npm and Electron. Use the the defaults, except for entry point:

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (ElectronWeather.appstudio) 
version: (1.0.0) 
description: 
entry point: (electronMain.js)
test command: 
git repository: 
keywords: 
author: 
license: (ISC) 
About to write to /Users/george/ElectronWeather.appstudio/package.json:

{
  "name": "ElectronWeather.appstudio",
  "version": "1.0.0",
  "description": "",
  "main": "electronMain.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Is this OK? (yes) yes

4. We can now add some libraries from npm to our project. In the same command line window, type the following:

npm install weather-js
npm install electron

5. Drag and drop package.json into the Project Explorer window in AppStudio. This adds the file to the project.

6. Create a file called electronMain.js in your project folder, with the following code in it:

// Modules to control application life and create native browser window
const {app, BrowserWindow, Menu} = require('electron');
const path = require('path');
const url = require('url');

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
  	width: 768,
  	height: 1004,
  	icon:__dirname+'/img/AppStudio.icns',
  	title: 'Framework Converter',
  	webPreferences: {nodeIntegration: true},
  	})
  console.log(__dirname)

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  mainWindow.webContents.openDevTools()
  
  // set up the menu
  const menu = Menu.buildFromTemplate(template)
	// Menu.setApplicationMenu(menu)	

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
})

7. Drag and drop electronMain.js into the Project Explorer window of AppStudio. In the file's properties, set loadType to 'noload'.

Add the Weather Code

1. Add a button to Form1.

2. In the code window for Form1, paste the following code: BASIC

weather = require("weather-js")
 
function Button1_onclick()
  weather.find({search: "San Francisco, CA", degreeType: "F"}, weatherFindCallback)
End function

function weatherFindCallback(err, result)
  If err Then
    MsgBox(err)
  else
    Print JSON.stringify(result, null, 2)
  End if
End function

JavaScript

var weather = require("weather-js");

Button1.onclick = function() {
  weather.find({search: "San Francisco, CA" , degreeType: "F"}, weatherFindCallback);
};

function weatherFindCallback(err, result) {
  if(err) {
    NSB.MsgBox(err);
 } else {
    NSB.Print(JSON.stringify(result, null, 2));
  }
}

Set up the Deploy

10. Set deploy option to a local path - something like local-deploy

11. deploy to it.

12. open a command window in local-deploy/ElectronWeather

13. npm install

14. npm start - the app should run

15. Add a button to Form1

16. Add this code to Form1. weather = require("weather-js")

function Button1_onclick()

 weather.find({search: "San Francisco, CA", degreeType: "F"}, weatherFindCallback)

End function

function weatherFindCallback(err, result)

 if err Then
   MsgBox(err)
 else
   Print JSON.stringify(result, null, 2)
 End if

End function

17. Add this to extraheaders:

Run the App