1. 程式人生 > >NW.js 簡介與使用

NW.js 簡介與使用

min net acc round getmenu too nbsp alt mac

簡介 (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();//需要手動刷新
                }
            });
        };

更多詳細的可以參考 http://liuxp.me/nwjs/References/Window/ 中文文檔

NW.js 簡介與使用