NW.js是什么如何使用

如题所述


本文主要和大家分享NW.js是什么如何使用?NW.js (原名 node-webkit)是一个基于 Chromium 和 node.js 的应用运行时,通过它可以用 HTML 和 JavaScript 编写原生应用程序。它还允许您从 DOM 调用 Node.js 的模块 ,实现了一个用所有 Web 技术来写原生应用程序的新的开发模式。
(1)以网络最流行的技术编写原生应用程序的新方法

(2)基于HTML5, CSS3, JS and WebGL而编写

(3)完全支持nodejs所有api及第三方模块

(4)可以使用DOM直接调用nodejs模块

(5)容易打包和分发

(6)支持运行环境包括32位和64位的Window、Linux和Mac OS

使用方法如下:
一、下载nw
1.下载 NW.js(官网:http://nwjs.io/)
这里面normal这个算是运行时吧,sdk那个是一些工具箱,建议都下下来~
https://nwjs.io/downloads/
2.下载 Enigma Virtual Box(官网:http://enigmaprotector.com/)
二、配置 package.json 文件
{
"name": "nw-demo",
"version": "0.0.1",
"main": "index.html"
}更多的可用如下:
{
"main": "app/index.html",
"name": "WeixinMenuEditor",
"description": "使用nw.js封装的一个微信公众号菜单编辑器App",
"version": "0.0.1",
"keywords": [ "微信", "菜单编辑器" ],
"window": {
"title": "微信菜单编辑器",
"icon": "app/static/img/weixin_logo.jpg",
"toolbar": true,
"frame": true,
"width": 1008,
"height": 750,
"position": "center",
"min_width": 400,
"min_height": 200
},
"webkit": {
"plugin": true,
"java": false,
"page-cache": false
},
"chromium-args" :"-allow-file-access-from-files"
}title : 字符串,设置默认 title。
width/height : 主窗口的大小。
toolbar : bool 值。是否显示导航栏。
icon : 窗口的 icon。
position :字符串。窗口打开时的位置,可以设置为“null”、“center”或者“mouse”。
min_width/min_height : 窗口的最小值。
max_width/max_height : 窗口显示的最大值。
resizable : bool 值。是否允许调整窗口大小。
always-on-top : bool 值。窗口置顶。
fullscreen : bool 值。是否全屏显示。
show_in_taskbar : 是否在任务栏显示图标。
frame : bool 值。如果设置为 false,程序将无边框显示。
"chromium-args" :"-allow-file-access-from-files" 相当于给谷歌浏览器添加启动参数一样,这行代码允许angularjs直接访问本地json文件。
三、生成exe
项目目录如下:
将html项目压缩成zip,并改名为nw,输入以下命令
copy /b nw.exe+app.nw firstApp.exe四、打发包发布
打开 Enigma Virtual Box 程序(enigmavb.exe),界面应该是这样的:
然后在 Enter Input File Name 处选择上一步生成的 test.exe 文件,Enter Output Name 可以默认;
之后再点击下面的 Add 按钮,将 nwjs 文件夹(名称不一定是 nwjs ,就是最开始第一步 NW.js 环境的那个文件夹)下除 nw.exe 和 test.nw 以及 test.exe 之外的所有文件加载上,然后点击 Process ,等待执行成功即可,这时候会在相应的路径下生成一个新的 .exe 文件(我们暂且叫做 newtest.exe),此时的 newtest.exe 文件即可在任意的 Windows 环境下运行了,你可以拷贝给你的小伙伴去 Show 一下。
下面是nw使用过程中的一些坑
1.如果只希望当前应用获取焦点才执行快捷键,看看这个库用js设置快捷键
// 加载本地ui库
var gui = require('nw.gui');
var option = {
key: "Ctrl+R",
active: function () {
alert("全局快捷键" + this.key + "按下");
},
failed: function (msg) {
//创建快捷键失败
alert(msg);
}
};
// 创建快捷键
var shortcut = new gui.Shortcut(option);
// 注册全局快捷键
gui.App.registerGlobalHotKey(shortcut);
// 解除注册,在应用结束的时候执行
gui.App.unregisterGlobalHotKey(shortcut);2.nw.js不能对页面多次刷新,各种不正常,这是由于刷新页面后重新加载js文件对变量重新赋值引起的bug。 解决方案
nw.js 读取和保存文件
<html>
<head>
<meta charset="utf-8"/>
<title>nw.js实现文件读写</title>
</head>
<body>
<input id="readFile" type="file" >读取文件</input>
<!-- 默认文件名为filename.html -->
<input id="writeFile" nwsaveas="filename.html" type="file">保存文件</input>
<p></p>
<script>
//nw.js提供的读写文件模块
var fs = require("fs");
//读文件
var chooser = document.querySelector('#readFile');
chooser.addEventListener("change", function (evt) {
//用户选择的文件
var filePath = this.value.toString();
document.querySelector("p").innerHTML = "读取文件从" + filePath;
fs.readFile(filePath, function (err, data) {
if (err) {
layer.msg("读取文件失败! :" + err.message);
return;
} else {
console.log(data);
alert(data);
}
})
});
//写文件
chooser = document.querySelector('#writeFile');
chooser.addEventListener("change", function (evt) {
//用户选择的文件
var filePath = this.value.toString();
document.querySelector("p").innerHTML = "写入文件到:" + filePath;
//把hello写入文件
fs.writeFile(filePath, "Hello!\n", function (err) {
if (err) {
alert("保存失败!");
}
});
});
</script>
</body>
</html>3.使用nwjs的'fs'直接保存cancas为本地图片,在网上找到的方法都是弹出选择框保存,但我需要直接保存图片到指定路径,不能弹出对话框让用户选择。kailniris给了一个解决方案,可行,代码如下:
var fs = require('fs');
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
base64Data = c.toDataURL("image/png").replace(/^data:image\/png;base64,/, "")
fs.writeFile("c:/Dev/test.png", base64Data, 'base64', function (err) {
if (err) {
console.log("err", err);
} else {
return res.json({ 'status': 'success' });
}
});用html2canvas把html页面转换为图片,再把图片保存到本地。贴一下代码(需要导入html2canvas.js和jquery):
//要保存图片的文件路径
var filePath = templateDir + filename + '.html';
//要保存的html页面
var editerDocument = window.editor.edit.iframe.get().contentWindow.document;
html2canvas(editerDocument.body, {
onrendered: function (canvas) {
var base64Data = canvas.toDataURL("image/png").replace(/^data:image\/png;base64,/, "")
var fs = require("fs");
fs.writeFile(templateDir + filename + '.png', base64Data, 'base64', function (err) {
if (err) {
alert("保存模板失败!");
}
$('#model_template_name').modal("hide");
layer.msg("模板已保存为" + filename);
});
}
});4.在app.js里引用Node内置模块
//调用NodeJs内置模块
$scope.fs = require('fs');
//读取配置文件
$scope.readConfig = function () {
try {
var configStr = $scope.fs.readFileSync(config.weixin.path, 'utf8');
console.log(configStr);
var obj = eval('(' + configStr + ')');
$scope.weixin.appid = obj.appid;
$scope.weixin.appsecret = obj.appsecret;
$scope.weixin.qrcodeurl = obj.qrcodeurl;
}
catch (e) {
console.log(e);
alert("读取微信配置文件失败");
}
}
//写入配置文件
$scope.writeConfig = function () {
try {
var configStr = JSON.stringify($scope.weixin);
$scope.fs.writeFileSync(config.weixin.path, configStr, {encoding: 'utf8'});
return true;
}
catch (e) {
console.log(e);
alert("写入微信配置文件失败");
return false;
}
}5.引用第三方模块wechat-api
//调用NodeJs第三方模块
$scope.wechatApi = require('wechat-api');
$scope.query = function () {
var api = new $scope.wechatApi($scope.weixin.appid, $scope.weixin.appsecret);
api.getMenu(function (err, result) {
if (err) {
console.log(err);
alert("查询菜单异常");
} else {
load(result);
$scope.$apply();//需要手动刷新
}
});
};
温馨提示:答案为网友推荐,仅供参考