Electron中使用bytenode保护nodejs代码实践

网上也看了不少把node javascript转换为bytecode的文章,但是实操起来总有些问题,特别是对preload.js部分怎么把preload.js转换为bytecode,说得不那么详尽;我把我自己实践过程详细的描述一下,希望可以帮到有需要的朋友;

1.我是在一个开源项目上简单修改一下,vue3-electron-serialport: vue-cli+vue-cli-plugin-electron-builder+node SerialPort搭建的基于vue3和element-plus串口工具。

Home.vue

/* eslint-disable no-bitwise */
<template>
  <div>
    <el-form>
      <el-form-item>
         渲染进程
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
/* eslint-disable */
import {
  reactive, ref, onUnmounted, watch, computed, nextTick,
} from 'vue';
import funtest1 from '../funtest1'
const toHexString = bytes =>
  bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '')+' ';
funtest1('call by Home');
const getForm = () => {    
    
  return {
  
  };
}

export default {
  name: 'Home',  
  setup() {
    return {
      ...getForm(),      
    };
  },
  methods: {
  }
};
</script>

 background.js

import {
  app, protocol, BrowserWindow, session, ipcMain,
} from 'electron';
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib';
// import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer';
const path = require('path');

const isDevelopment = process.env.NODE_ENV !== 'production';

app.allowRendererProcessReuse = false;
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } },
]);


// 测试 Node API
// const bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// const buf = Buffer.from(bytes);
// console.log('backgroud,buf', buf);

async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      contextIsolation: true,
      preload: path.join(__dirname, '/preload.js'),
    },
  });

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol('app');
    // Load the index.html when not in development
    win.loadURL('app://./index.html');
  }
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // 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', () => {
  // 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 (BrowserWindow.getAllWindows().length === 0) createWindow();
});

// 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', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    // try {
    //   await installExtension(VUEJS_DEVTOOLS);
    //   session.defaultSession.loadExtension(
    //     path.resolve(__dirname, '../../vue-devtools/shells/chrome'), // 这个是刚刚build好的插件目录
    //   );
    // } catch (e) {
    //   console.error('Vue Devtools failed to install:', e.toString());
    // }

    // 记得预先安装 npm install vue-devtools
    const ses = session.fromPartition('persist:name');
    try {
      // The path to the extension in 'loadExtension' must be absolute
      await ses.loadExtension(path.resolve('node_modules/vue-devtools/vender'));
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString());
    }
  }
  createWindow();
});

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit();
      }
    });
  } else {
    process.on('SIGTERM', () => {
      app.quit();
    });
  }
}

preload.js

const funtest1 = require('./funtest1');
const bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const buf = Buffer.from(bytes);
console.log('preload,buf', buf);
funtest1('call by preload');

funtest1.js

function stringToUint8Array(str){
  var arr = [];
  for (var i = 0, j = str.length; i < j; ++i) {
    arr.push(str.charCodeAt(i));
  }
 
  var tmpUint8Array = new Uint8Array(arr);
  return tmpUint8Array
}

function funtest1(str) {
  console.log("str",str);
  const buf = Buffer.from(str);
  //const buf = stringToUint8Array(str);
  console.log("buf:",buf);
}

module.exports = funtest1;

执行

npm run electron:serve

在console里面看日志,可以发现那个 Buffer.from 返回的对象在preload.js 里面跟在 Home.vue里面返回的对象类型是不一样的,在 Node.js 中,Buffer 类是随 Node 内核一起发布的核心库,在普通的Web里面的Javascript环境是调用不了的,

我这个是使用 Electron13.6.2版本,在渲染进程里面能使用Buffer.from,感觉应该跟早期版本渲染进程可以直接调用Nodejs API有关系,虽然新版在渲染进程中不能通过require调用Node API,但是调用Node核心库好像没有问题;我说这个跟下面的内容是有关系的,先做个铺垫;

下面来说说如何使用bytenode;先安装

npm install --save bytenode

修改下package.json,在  scripts 里面增加

"pack": "vue-cli-service electron:build --skipBundle"

在 vue.config.js里面的增加

 electronBuilder: {
      preload: 'src/preload.js',
     builderOptions: {
     ...

这样build的时候才会把 preload.js 打包进去;

执行打包

npm run electron:build

在 dist_electron\win-unpacked\resources\app 目录下可以看到,跟   dist_electron\bundled  是一样的

下面的使用bytenode的方法是学习自 https://gitee.com/qjh_2413/vue-electron-bytenode.git

1.在bundled里面把 backgroud.js 重命名为 backgroud.src.js,把 preload.js重命名为 preload.src.js,新建 background.bytenode.js和 preload.bytenode.js

background.bytenode.js

'use strict';

const bytenode = require('bytenode');
const fs = require('fs');
const v8 = require('v8');
const path = require('path');

v8.setFlagsFromString('--no-lazy');

if (!fs.existsSync(path.join(__dirname, './background.jsc'))) {
  bytenode.compileFile(path.join(__dirname, './background.src.js'),path.join(__dirname,  './background.jsc'));
}

require(path.join(__dirname,'./background.jsc'));

preload.bytenode.js

'use strict';

const bytenode = require('bytenode');
const fs = require('fs');
const v8 = require('v8');
const path = require('path');

v8.setFlagsFromString('--no-lazy');

if (!fs.existsSync(path.join(__dirname, './preload.jsc'))) {
  bytenode.compileFile(path.join(__dirname, './preload.src.js'),path.join(__dirname,  './preload.jsc'));
}

require(path.join(__dirname,'./preload.jsc'));

把 background.bytenode.js 复制一份为 backgroud.js,把 preload.bytenode.js复制为 preload.js,

网上有说用 electron .\background.js ,但是经常有人碰到错误,其实就是因为你调用的electron版本跟当前项目的版本不一致;你可以直接使用 .\node_modules\electron\dist\electron.exe .\dist_electron\bundled\background.js   ,用当前项目的electron来执行background.js;

另一种更简单,在 dist_electron\win-unpacked\resources\app 执行跟上面一样的步骤(electronbuilder里面的 asar 先设为 false),然后执行 dist_electron\win-unpacked\(项目).exe,然后把 backgroud.jsc,background.js,preload.jsc,preload.js复制到 bundled 目录里面;

然后执行打包

npm run pack

但是你会发现

preload.js里面调用 Buffer.from 报错,因为 preload.js 生成preload.jsc时是在渲染进程执行的,普通的浏览器javascript环境是调用不了 Buffer.from 这个 Nodejs API的。要解决这个问题,把生成 preload.jsc这个步骤放到 background.js执行,

修改 background.js

'use strict';

const bytenode = require('bytenode');
const fs = require('fs');
const v8 = require('v8');
const path = require('path');

v8.setFlagsFromString('--no-lazy');

if (!fs.existsSync(path.join(__dirname, './background.jsc'))) {
  bytenode.compileFile(path.join(__dirname, './background.src.js'),path.join(__dirname,  './background.jsc'));
}

if (!fs.existsSync(path.join(__dirname, './preload.jsc'))) {
  bytenode.compileFile(path.join(__dirname, './preload.src.js'),path.join(__dirname,  './preload.jsc'));
}

require(path.join(__dirname,'./background.jsc'));

然后在 preload.js里面把生成 preload.jsc 这段代码注释掉,你发现可以正确执行,调用Buffer.from 也不报错了;

我也实验了一下 在 preload.js 里面生成 background.jsc,

修改 preload.js

'use strict';

const bytenode = require('bytenode');
const fs = require('fs');
const v8 = require('v8');
const path = require('path');

v8.setFlagsFromString('--no-lazy');

if (!fs.existsSync(path.join(__dirname, './preload.jsc'))) {
  bytenode.compileFile(path.join(__dirname, './preload.src.js'),path.join(__dirname,  './preload.jsc'));
}

if (!fs.existsSync(path.join(__dirname, './background.jsc'))) {
  bytenode.compileFile(path.join(__dirname, './background.src.js'),path.join(__dirname,  './background.jsc'));
}

require(path.join(__dirname,'./preload.jsc'));

我说下结果吧,如果 background.js 里面不调用 Buffer.from,生成的 background.jsc执行没有报错,background.js里面通过require引用Nodejs API都没有问题,如果我在background.js加上

 const bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 const buf = Buffer.from(bytes);
 console.log('backgroud,buf', buf);

启动就会报错,

应用启动不起来;

 总结:background.js,preload.js这些要转换成bytecode还是在主线程里面执行比较好;

最新更新:把bytenode 编译放入打包流程,请看项目:vue3-electron-bytenode: 把 bytendoe 应用到 electron-builder 构建流程实践;

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Node.js 使用 Electron 来渲染 Cesium,您需要遵循以下步骤: 1. 安装 Electron 您可以使用 npm 安装 Electron:`npm install electron --save-dev` 2. 安装 Cesium 您可以从 Cesium 的官方网站下载最新版本的 Cesium 并解压缩到您的项目。 3. 在 Electron 使用 Cesium 在 Electron 使用 Cesium 的方法是创建一个 HTML 文件,包含 Cesium 的 JavaScript 和 CSS 文件,然后使用 Electron 的 BrowserWindow 模块来加载这个 HTML 文件。以下是一个示例代码: ```javascript const { app, BrowserWindow } = require('electron') const path = require('path') function createWindow() { const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js') } }) mainWindow.loadFile('index.html') } app.whenReady().then(() => { createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) ``` 在这个示例,我们创建了一个 BrowserWindow 并加载了一个名为 `index.html` 的文件。在 `index.html` 文件,我们引入了 Cesium 的 JavaScript 和 CSS 文件,并在页面上创建了一个 Cesium Viewer: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello Cesium!</title> <link href="Cesium/Widgets/widgets.css" rel="stylesheet"> <script src="Cesium/Cesium.js"></script> </head> <body> <div id="cesiumContainer"></div> <script> var viewer = new Cesium.Viewer('cesiumContainer'); </script> </body> </html> ``` 这样就可以在 Electron 使用 Cesium 来渲染地球了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值