androllen / KnowlegeRepository

0 stars 0 forks source link

ElectronJs #33

Open androllen opened 4 years ago

androllen commented 4 years ago

https://electronjs.org

androllen commented 3 years ago

https://github.com/nodejs/node/blob/master/doc/abi_version_registry.json

https://nodejs.org/zh-cn/download/releases/

androllen commented 3 years ago

sqlite

yarn add sqlite3

const { join, dirname } = require('path');
const sqlite3 = require('sqlite3').verbose()
const dbPath = join(dirname(__dirname), 'sql', 'sql.db');
let db

function init() {
    if (!db) {
        db = new sqlite3.Database(dbPath)
    }
}

function queryData(sql, callback) {
    init();
    db.all(sql, function (err, rows) {
        if (null != err) {
            printErrorInfo(err);
            return;
        }

        /// deal query data.
        if (callback) {
            callback(rows);
        }
    });
};

function GetMd5_16(params, dataDeal) {
    let querySql = 'SELECT * FROM md5 WHERE md5_16=' + "\'" + params + "\'";
    console.log(querySql);

    queryData(querySql, dataDeal);

}

function dataDeal(objects) {
    for (let i = 0; i < objects.length; ++i) {
        console.log(objects[i]);
    }
}

init()
GetMd5_16('ac59075b964b0715', dataDeal)
SELECT * FROM md5 WHERE md5_16='ac59075b964b0715'
{
  md5_32: '202cb962ac59075b964b07152d234b70',
  md5_16: 'ac59075b964b0715',
  sn: '123'
}
androllen commented 3 years ago
"vetur.format.defaultFormatterOptions": {
    "prettyhtml": {
      "printWidth": 160
    },
    "prettier": {
      "singleQuote": true,
      "proseWrap": "never",
      "printWidth": 130
    }
  },
androllen commented 3 years ago

vscode debug vue

Enable sourcemaps in your vue.config.js

module.exports = {
  configureWebpack: {
    devtool: 'source-map'
  }
}

tasks.json

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
    {
      "label": "electron-debug",
      "type": "process",
      "command": "./node_modules/.bin/vue-cli-service",
      "windows": {
        "command": "./node_modules/.bin/vue-cli-service.cmd"
      },
      "isBackground": true,
      "args": ["electron:serve", "--debug"],
      "problemMatcher": {
        "owner": "custom",
        "pattern": {
          "regexp": ""
        },
        "background": {
          "beginsPattern": "Starting development server\\.\\.\\.",
          "endsPattern": "Not launching electron as debug argument was passed\\."
        }
      }
    }
  ]
}

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Electron: Main",
      "type": "node",
      "request": "launch",
      "protocol": "inspector",
      "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
      "windows": {
        "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron.cmd"
      },
      "preLaunchTask": "electron-debug",
      "args": ["--remote-debugging-port=9223", "./dist_electron"],
      "outFiles": ["${workspaceFolder}/dist_electron/**/*.js"]
    },
    {
      "name": "Electron: Renderer",
      "type": "chrome",
      "request": "attach",
      "port": 9223,
      "urlFilter": "http://localhost:*",
      "timeout": 30000,
      "webRoot": "${workspaceFolder}/src",
      "sourceMapPathOverrides": {
        "webpack:///./src/*": "${webRoot}/*"
      }
    }
  ],
  "compounds": [
    {
      "name": "Electron: All",
      "configurations": ["Electron: Main", "Electron: Renderer"]
    }
  ]
}

打断点 选择调试 中 Electron: All

androllen commented 3 years ago

加载本地库依赖 比如 sqlite zeromq 串口通信库

vue.config.js

module.exports = {
    pluginOptions: {
        electronBuilder: {
            // List native deps here if they don't work
            externals: ['sqlite3'],
            nodeIntegration: true,
            // If you are using Yarn Workspaces, you may have multiple node_modules folders
            // List them all here so that VCP Electron Builder can find them
            nodeModulesPath: ['./node_modules']
        }
    },
    configureWebpack: {
        devtool: 'source-map'
    }
}

App.vue

<script>
const path = require('path');
let md5Sqlite = require('sqlite3').verbose();
const dbPath = path.join(__static, 'sql.db');
let db;

function init() {
  if (!db) {
    try {
      console.log(dbPath);
      db = new md5Sqlite.Database(dbPath);
      console.log('create ok');
    } catch (error) {
      console.log('dirname');
      console.log(error);
    }
    console.log('create end');
  }
}

function queryData(sql, callback) {
  init();
  console.log('entry db');

  db.all(sql, function (err, rows) {
    console.log('entry db.all');
    if (null != err) {
      printErrorInfo(err);
      return;
    }
    if (callback) {
      callback(rows);
    }
  });
}

function printErrorInfo(params) {
  console.log(params);
}

function GetMd516(params, dataDeal) {
  let querySql = 'SELECT * FROM md5 WHERE md5_16=' + "'" + params + "'";
  console.log(querySql);
  queryData(querySql, dataDeal);
}

function GetMd532(params, dataDeal) {
  let querySql = 'SELECT * FROM md5 WHERE md5_32=' + "'" + params + "'";
  console.log(querySql);
  queryData(querySql, dataDeal);
}

function dataDeal(objects) {
  console.log('begin deal');
  for (let i = 0; i < objects.length; ++i) {
    console.log(objects[i]);
  }
}

GetMd516('ac59075b964b0715', dataDeal);
androllen commented 3 years ago

添加本地文件

__static Available only in Electron

https://nklayman.github.io/vue-cli-plugin-electron-builder/guide/guide.html#handling-static-assets

https://cli.vuejs.org/guide/html-and-static-assets.html#the-public-folder

# App.vue
// 
<script>
// Only works in electron serve/build
// Will not work in renderer process unless you enable nodeIntegration
// 把 myText.txt 放进 public folder 中
// __static 相对于 是public 文件夹路径

const fs = require('fs')
const path = require('path')

const fileLocation = path.join(__static, 'myText.txt')
const fileContents = fs.readFileSync(fileLocation, 'utf8')

console.log(fileContents)
</script>
androllen commented 3 years ago

Icons

Tray Icon

// Import path module (at the top of your file, below 'use-strict')
+import path from 'path'

const win = new BrowserWindow({
  width: 800,
  height: 600,
  webPreferences: {
    // Use pluginOptions.nodeIntegration, leave this alone
    // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
    nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION
  },
+ icon: path.join(__static, 'icon.png')
})
androllen commented 3 years ago

打开对话框选择文件

const { dialog } = require('electron').remote
const selectDirBtn = document.getElementById('select-directory')
selectDirBtn.addEventListener('click', (event) => {
  dialog.showOpenDialog({
    title: "打开文件",
    defaultPath: "",
    properties: ['openFile', 'multiSelections'],
    filters: [
      { name: 'Text', extensions: ['txt'] },
      { name: 'All Files', extensions: ['*'] }
    ]
  }).then(result => {
    console.log(result.filePaths);
  })
})

remote 模块使用为了在主进程和渲染进程之间通信

打开对话框保存文件

const { dialog } = require('electron').remote
const selectDirBtn = document.getElementById('select-directory')
selectDirBtn.addEventListener('click', (event) => {
  dialog.showSaveDialog({
    title: "保存文件",
    defaultPath: "",
    properties: ['saveFile'],
    filters: [
      { name: 'Text', extensions: ['txt'] },
      { name: 'All Files', extensions: ['*'] }
    ]
  }).then(result => {
    const fs = require('fs');

    var fd = fs.openSync(result.filePath, 'w');
    fs.writeSync(fd, info);
    fs.closeSync(fd);
  }).catch(err => {
    console.log(err)
  })
})
androllen commented 3 years ago

构建 https://www.electronjs.org/docs/tutorial/application-packaging https://github.com/electron/electron-packager

方法一

yarn add electron-packager -g
electron-packager . --electron-version=9.3.3 --download.mirrorOptions.mirror=https://npm.taobao.org/mirrors/electron/ --overwrite --platform=win32 --arch=x64 --out=./out 

方法二 不太建议使用,未测试

https://npm.taobao.org/mirrors/electron/9.0.0/ or https://github.com/electron/electron/releases/

下载 https://npm.taobao.org/mirrors/electron/9.0.0/electron-v9.0.0-win32-x64.zip 下载 curl -o SHASUMS256.txt-9.0.0 https://npm.taobao.org/mirrors/electron/9.0.0/SHASUMS256.txt 放到 C:\Users\dogs\AppData\Local\electron\Cache