preface

Recently, we have received the development demand at work. The company wants to sell the server hardware (based on Linux operating system) running in special scenarios. Front-end engineers need to cooperate with the development of graphical applications under Linux system for delivery.

Finally, the required application program directly obtains the current computing data and related parameters of the machine by calling the shell script written by the hardware engineer, and then renders the interface for the user to view. The whole process is connected by the front end and the hardware engineer, without the involvement of the back end.

Due to my previous experience in using Electron to develop client software under Windows, I still choose Electron as the technical solution to achieve the development goal.

Electron is a framework for creating native applications using Web technologies such as JavaScript, HTML, and CSS. It integrates Chromium and Node.js internally, enabling common browsers to call operating system related services. In addition, its biggest advantage is that it can develop client applications supporting Windows, Mac and Linux systems.

Front-end engineers generally have little exposure to Linux operating system, so it is not a small challenge to quickly familiarize themselves with system features and achieve development goals with the minimum learning cost. The whole development flow is roughly summarized as the following steps.

  • Set upLinuxOperating system and graphical desktop
  • Set upElectronProject architecture, according toUIDesign drawings complete the development of static pages
  • After the static page is complete, write the callshellScript function, by calling the script to get machine data, and then render to the page
  • After the project is developed, package it into an installation program for delivery

Install the Linux development environment

Setting up the Linux environment is very complicated. Many people choose to install the VM and operating system locally, and then set up the environment. In order to use the Linux system quickly and easily in the early stage, you can consider buying a short-term and fully installed server on Aliyun with dozens of yuan.

First log in to the official website of Aliyun to register an account, and then select lightweight application server from the drop-down list in the product bar (as shown below).

After the page is displayed, select Configuration. In the application image column, select node. js 14.15.2 (as shown below). If you choose a Node version too low, many applications will not work.

In the image column, select Ubuntu 16.04 (as shown in the following figure). Select an OS image based on actual requirements. CentOs and Ubuntu are the most popular operating systems in Linux.

The configuration process is simple, it’s basically over here, and then click ok to pay and get a server.

Click the management console after the payment is successful, and the page displays the parameters of the server you purchased, such as the IP address of the public network,CPU usage and memory usage.

There is a reset password on the right side of the server information column. Click To set a new password and restart the application.

After the restart, click remote Connection on the upper right side (as shown below) and enter Node -v in the black window to view the Node version. The black window is a command line tool where you can enter various commands to complete system operations.

Sudo apt-get install git to install git on our server. Apt-get is a package management tool, we can use it to download, update, uninstall and other operations, similar to the front-end use of NPM.

Is this OK [y/N]: : Is this OK [y/N]: After the installation, enter git –version on the cli to view the installed Git version.

Install the graphical desktop

Our goal was to develop a graphical application under Linux, and a system with a black window on it would not suffice. We also need to install a graphical desktop on Linux, just like Windows, so that our applications can be displayed on the graphical desktop.

  • To update the download source, type sudo apt-get update on the command line.

  • To install desktop xfCE, run sudo apt install xfce4.

VNC configuration

VNC is configured so that a local Windows PC can open a remote server as a graphical desktop.

Run sudo apt-get install vnc4server to install VNC.

After the VNC server is installed, run the vncserver :1 command to start VNC. The first time you start up, you will enter the connection password. Remember the password. Later, you will need this password when you connect to the remote desktop from local Windows.

After the password is set, modify the VNC configuration file. Run the vncserver -kill :1 command to prevent errors when modifying files.

Run the vi ~/. VNC /xstartup command to open the VNC startup configuration file and enter the vi editor mode.

For those of you who have learned the basics of Linux, the VI editor has its own rules for entry and exit. By default, when you type a character on the keyboard, it will not appear in the file until you enter I into insert mode.

Type I to enter insert mode, then type the # comment in front of the x-window-manager & line, and paste the following configuration information below (the final result is shown below).

sesion-manager & xfdesktop & xfce4-panel &
xfce4-menu-plugin &
xfsettingsd &
xfconfd &
xfwm4 &
Copy the code

To exit the VI editor, press ESC in the upper left corner of the keyboard to Enter the command mode, type :wq, and press Enter to save the configuration and exit.

The above has roughly finished the SERVER VNC configuration, now enter ali Cloud console to configure the firewall, click firewall in the left security bar of the console (as shown below).

There is a button to add rules in the upper right corner, and a pop-up box appears after clicking it (as shown below). Select TCP as the protocol, enter 5901 as the port number, and finally click OK.

After the firewall is configured, go back to the console and restart the server (be sure to restart it again here) to open the remote connection (as shown below).

Wait until the command line window appears and type vncserver :1 to start the VNC service. At this point, the server configuration is complete.

The remote connection

The server has been configured. Now install the VNC client software on the local Windows PC to connect to the remote desktop.

Open the website https://www.realvnc.com/en/connect/download/viewer/ click on the download Windows client software installation.

Click “Run” after the software is installed. Click “New Connection” under “File” in the menu bar and a pop-up box appears. Enter the public IP address of the purchased Aliyun host in the column of VNC Server, and add the upper end number 5901(as shown in the following figure). Click OK when the configuration is complete.

An icon is displayed on the home screen. After you tap it, you are asked to enter the password. The password is the same as that set for configuring VNC Server on the Server.

After the password is entered, the remote desktop is opened (as shown below) and all Linux system configuration is complete.

Sometimes it is found that the remote desktop cannot be connected after the Ali cloud server restarts. At this time, it is necessary to open the command line tool of Ali Cloud console and enter vncServer :1 to start the VNC service and then connect to the remote desktop.

Electron Project development

The graphical interface is already up and running, similar to Windows.

We are now working on Electron. At present, there are many excellent Electron scaffolds on Githup. Of course, we have enough time and special requirements to build them by ourselves.

Scaffolding is convenient for those unfamiliar with the Electron front end, eliminating the need for complex project construction. At present, the popular scaffolding is the react based electron- React – Boilerplate. The project address is as follows.

https://github.com/electron-react-boilerplate/electron-react-boilerplate

If you are a VUE enthusiast, you can also choose the electron- Vue scaffolding, the project address is shown below.

https://github.com/SimulatedGREG/electron-vue

In this paper, electron-react- Boilerplate is taken as an example. Right-click on the Linux graphics desktop and choose Open Terminal Here to Open the command line tool.

Since we already have Git installed, we can clone the project directly using Git.

Run the command git clone https://github.com/electron-react-boilerplate/electron-react-boilerplate download project to the desktop.

If it is found that githup won’t open, can be downloaded into the command git clone git://github.com/electron-react-boilerplate/electron-react-boilerplate – the depth of 1.

After the download is complete, click on the project folder into the project directory, for the rest of the installation work carried out smoothly, will open out the current project folder permissions, execute the command sudo chmod -r 777 / home/admin/Desktop/electron – react – boilerplate. By default, the project name here is electron-react-boilerplate. If you change other names, you will need to change them accordingly.

After permission modification, go to the project folder, click the right mouse button to open the command line in this directory, enter sudo NPM install -g CNPM, and then use sudo CNPM install to install dependencies (NPM installation may fail). After the dependencies are installed, open the project file package.json and find that the project start command is NPM run start.

NPM run start starts the project. During startup, the command line tool is stuck (as shown below). This is because the Browser debugging tool that installed React requires access to the Chrome App Store, and the command line is stuck because it cannot be accessed.

To resolve the above problem, open SRC /main.dev.ts in the project directory and comment out the line await installExtensions(). This comment simply uninstalls the React debug tool, and the Electron debug window will remain.

When the project is finally started, open the project directory SRC/app.tsx and change the code of the root component to Hello World.

const Hello = () => {
  return (
    <div>
       Hello world
    </div>
  );
};
export default function App() {
  return (
    <Router>
      <Switch>
        <Route path="/" component={Hello} />
      </Switch>
    </Router>
  );
}
Copy the code

It is recommended not to write code under Linux in actual development, because graphical desktops are not very stable and often lag affects development efficiency. The optimal solution is to write the code in Windows and submit it to Git after development. The Linux server directly pulls the final code from Git and runs it to observe the effect. If all the effects are as expected, it will be packaged into an installation package.

Running shell scripts

The electron-react- Boilerplate scaffolding is based on the React framework, and the process of developing the page is the same as we normally develop the page.

If you’re just developing web content, the page can be packaged and delivered. But our development goal is to be able to call shell scripts to get data. The source of the data is no longer fetched from the back end as before, but instead calls the script directly to fetch the data to render.

Shell is a command line interpreter. It provides users with an interface system level program that sends requests to the Linux kernel to run programs. Users can start, suspend, stop and even write some programs with shell.

For example, here we write a simple shell script file getsystem.sh to getSystem status information.

#! /bin/bash echo -e "hostname:\t `hostname`" echo -e "OScore:\t\t `uname -a`" echo -e "CPUInfo:\t `grep "model name" /proc/cpuinfo | awk -F: '{print $2}' ` " echo -e "CPUMHz:\t\t `grep "MHz" /proc/cpuinfo | awk -F: '{print $2}' ` " echo -e "MemTotal:\t `free -m | awk '$1=="Mem:" {print $2}' ` "Copy the code

Echo indicates output. The five output statements correspond to the following five data items.

  • Gets the local host name
  • Obtain the version number of the system
  • Gets the CPU type
  • Obtain the CPU working frequency
  • Gets memory usage

How do I execute a shell script file? You can run the /bin/bash getSystem.sh command to execute the script file. After executing the script file, the following figure is displayed.

Now that you’ve just printed the data on the command line, you need to display it on the page.

Now create a new folder scripts in the SRC folder in the root of the project to store all shell scripts, create a new file getSystem.sh as a test demo, and assign the script code to getSystem.sh.

The shell script is ready, we also need to configure the files under the build field in pacakge.json in the root directory of the project, and configure the folder containing the shell script into it (as shown below).

The configuration of these files are static resources, equivalent to the public folder in Web development, and webpack will copy them to the packaged directory after the final package.

Now that the shell script is configured, how do you find the script path on the page and execute it?

Since Electron integrates NodeJS, we can execute commands directly using node’s child process module child_process (code below).

const path = require("path"); const exec = require("child_process").exec; Const Hello = ()=>{const getSystem = ()=>{// getSystem parameters // with the configuration above, the scripts folder will be copied directly into the packaged folder as a static resource script_path = path.join(__dirname, "scripts", 'getSystem.sh'); console.log(script_path); Exec (' /bin/bash ${script_path} ', (error,stdout) => {// execute script if(! Error){console.log(" script output :"+stdout); Return (<div> <button onClick={getSystem}> click </button> </div>); };Copy the code

As expected, clicking the button eventually returns the output of the script after execution. But when tested packaged, the path of the script output from the console after the above code runs looks like this (figure below).

We will find the getsyetem. sh script file inside app.asar, the compressed format file of Electron program, which is equivalent to the shell of the program. All the source code is completely encapsulated inside itself, forming an isolated sandbox environment.

Therefore, the external system cannot obtain the file in app.asar. If /bin/bash is used to forcibly execute the shell script wrapped in app.asar, an error will be reported.

Since direct execution is not possible, we need to change the idea. When executing the script file, copy the script to a temporary folder of the system and use /bin/bash to execute the script in the temporary folder.

Let’s create a new tool method called Call (code below).

/ TMP/myScripts/TMP/myScripts/TMP/myScripts/TMP/myScripts/TMP/myScripts/TMP/myScripts

After the myScripts folder is created, copy the static script stored in electron to the myScripts folder and call /bin/bash to execute the script to return the result.

const path = require("path"); const exec = require("child_process").exec; const fs = require('fs-extra'); Export const call = (name)=>{const script_path = path.join(__dirname, "scripts", '${name}.sh'); Return new Promise(async (resolve,reject)=>{await fs.ensuredir ('/ TMP /myScripts'); Const dist_path = '/ TMP /myScripts/${name}. Sh'; const isExit = await fs.pathExists(dist_path); // The script already exists! isExit && await fs.copy(script_path, dist_path); Exec (' /bin/bash ${dist_path} ', (error, stdout) => {if(error){console.log(error); reject(error); }else{ resolve(stdout); // Return the data result of the script}}); }}})Copy the code

Call the call function directly from the page. If you want to call the script, pass in the file name of the script.

const Hello = () => {
  const getSystem = async ()=>{
    const data = await call("getSystem"); // 调用 getSystem.sh脚本
    console.log(data); //脚本执行完后返回的数据
  }  

  return (
    <div>
      <button onClick={getSystem}>点击</button>
    </div>
  );
};
Copy the code

Finally, clicking the button on the page causes Linux to execute the getSystem.sh script and returns the result.

The way of data acquisition has been smooth, the next work is to develop page rendering data, this part of the work and the development of front-end web page is no different.

packaging

Once the code is developed, it’s time to package it. First open package.json in the root directory of the project and look for the package command under scripts. It is package.

Enter sudo NPM run package directly from the command line to start the packaging process. Scaffolding is smart enough to determine the platform on which the code is currently running and generate the appropriate installation package.

After the command is successfully executed, a tape is generated in the project root directory release. A file with the suffix AppImage, which is the final application generated under Linux.

Unlike installation formats such as.appimage and.deb, it uses a common software format that can be used in almost all Linux distributions and can contain all functionality in a single package.

It is equivalent to the Windows system in those exe files free of installation, can be transmitted through software, U disk copy to carry on program mutual transmission. Any other Linux machine that receives the program can launch the application by double-clicking the mouse, making it easy to use.

The final result is as follows.

The source code

Download the code