NW.js 簡介與使用方法,nw.js簡介使用方法

來源:互聯網
上載者:User

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" 相當於給Google瀏覽器添加啟動參數一樣,這行代碼允許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 簡介與使用方法,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.