Node.JS 可以开发桌面应用. 目前用 Node.JS 开发桌面应用, 主要有两种方案: NW.JS 和 Electron 框架. NW.JS 是 Intel 的工程师写的一个基于 node.JS 和 chromium 的应用程序运行环境. Electron 是一款利用 web 技术开发跨平台桌面应用的框架.
下面给大家简单介绍一下使用 Electron 进行 Node.JS 的桌面应用开发.
- ## 开发环境及版本号 ##
- Node.JS : 7.2.0
- Electron : 1.4.10
- ## 开始教程 ##
安装各个应用:
安装 electron 的包
NPM install -g electron
安装 aser 打包工具
NPM install -g asar
安装 packager 发布工具
NPM install -g electron-packager
建立空的 Node.JS 项目:
NPM init
建立 JS 程序 index.JS :
- const {App, BrowserWindow} = require('electron')
- const path = require('path')
- const url = require('url')
- // Keep a global reference of the Windows object, if you don't, the Windows will
- // be closed automatically when the JavaScript object is garbage collected.
- let win
- function createWindow () {
- // Create the browser Windows.
- win = new BrowserWindow({width: 800, height: 600,autoHideMenuBar :true})
- win.setMenu(null);
- // and load the index.html of the App.
- win.loadURL(url.format({
- pathname: path.join(__dirname, 'index.html'),
- protocol: 'file:',
- slashes: true
- }))
- // Open the DevTools.
- //win.webContents.openDevTools()
- // Emitted when the Windows is closed.
- win.on('closed', () => {
- // Dereference the Windows 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.
- win = 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', () => {
- // 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 Windows in the App when the
- // dock icon is clicked and there are no other Windows open.
- if (win === null) {
- createWindow()
- }
- })
- // In this file you can include the REST of your App's specific main process
- // code. You can also put them in separate files and require them here.
package.JSON 中添加依赖, 最终的格式:
- {
- "name": "app",
- "version": "1.0.0",
- "description": "",
- "main": "index.js",
- "scripts": {
- "test": "echo \"Error: no test specified\"&& exit 1"
- },
- "author": "",
- "license": "ISC",
- "dependencies": {
- "electron": "^1.4.10"
- }
- }
当然你也可以用 NPM start 执行在 scripts 中添加 start 的命令
添加 index.HTML 文件:
- <!DOCTYPE HTML>
- <HTML>
- <head>
- <meta charset="UTF-8" />
- <title>
- Hello World
- </title>
- </head>
- <body>
- Hello World!
- </body>
- </HTML>
然后执行运行命令:
electron .
. 是指当前目录
开始打包, 进入项目:
asar abc path App.asar
然后到 App.asar 目录下开始发布:
electron-packager abc --all
至此当前目录下会有一个可执行程序的目录进入点开 exe 程序就可以了
来源: http://www.css88.com/qa/node-js/12027.html