2015年1月13日 星期二

【Javascript】匯出 csv

將 table 的內容匯出成 csv 檔案
利用 encodeURIComponent
將字串轉為 Data URI
但要注意轉出的 code 為 UTF-8 編碼
若直接用 Microsoft Office Excel 開啟 csv 檔案時
中文會變成亂碼
因為 Excel 無法預設讀取 UTF-8 編碼的 CSV 檔案
所以利用增加 UTF-8 BOM 的方式
讓 Excel 直接開啟 csv 不會出現亂碼
navigator.appVersion.indexOf("Win") 若回傳值不為 -1
表示 OS 為 Windows 系列
指定 charset 為 帶 BOM 的 UTF-8

產生 CSV 內容的資料處理部分
傳入的參數 _csvString
除了每列資料要加斷行符號
不同欄位之間的資料要加逗號之外
還要額外處理兩個地方
1.資料若含有特殊符號,例如逗號,資料需加上雙引號
2.資料內容若已有雙引號,建議用 replace 取代為兩個雙引號
這樣用 Excel 開啟時,瀏覽效果較佳
function exportToCSV( _csvString ) {
    var downloadLink = document.createElement("a");
    downloadLink.download = "dataTable.csv";
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null) {
        var code = encodeURIComponent( _csvString );
        if ( navigator.appVersion.indexOf("Win")==-1 ) {
            downloadLink.href = "data:application/csv;charset=utf-8," + code;
        } else {
            downloadLink.href = "data:application/csv;charset=utf-8,%EF%BB%BF" + code;
        }
    }

    downloadLink.click();
}

2015年1月8日 星期四

【Javascript】匯出txt


因為有將 Log 直接寫進 html 裡面
所以就想說將網頁上的純文字內容輸出為一個 txt 檔案
saveTextAsFile function 內有兩個參數
第一個參數 _fileName 為預設在本地端存檔的檔名
第二個參數 _text 為輸出的純文字內容

function saveTextAsFile( _fileName, _text ) {
    var textFileAsBlob = new Blob([_text], {type:'text/plain'});

    var downloadLink = document.createElement("a");
    downloadLink.download = _fileName;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null) {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    } else {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
}

function destroyClickedElement(event) {
    document.body.removeChild(event.target);
}

2014年9月24日 星期三

【Ubuntu】postgreSQL 本地備份

以下文章所出現家目錄,為安裝 PostgreSQL 的帳號之家目錄
例如是使用 user 帳號安裝 PostgreSQL
在家目錄新增檔案 .pgpass
檔案內容只有一行
localhost:port:database:username:password
localhost: 輸入 ip;若為本機端,輸入 127.0.0.1
port: port of PostgreSQL
database: 資料庫名稱
username: 資料庫帳號
password: 資料庫密碼

修改 .pgpass 的權限為 600
sudo chmod 600 .pgpass

新增備份目錄,測試匯出資料庫是否不用輸入密碼,若不用則上述設定成功
mkdir dbbackup
pg_dump -h 127.0.0.1 -p 5432 -U postgres postgres>postgres.dump

在家目錄新增檔案 backupdb.sh ,檔案內容如下
#!/bin/bash

#設定時間變數
day=$(date +%Y%m%d)
#設定備份路徑
bkdir="/home/user/dbbackup"
#備份資料庫
pg_dump -h 127.0.0.1 -p 5432 -U postgres postgres>"$bkdir"/postgres.dump
#移動到備份目錄
cd "$bkdir"
#壓縮資料庫並加上日期
tar -zcf postgres."$day".tar.gz postgres.dump
#刪除備份檔
rm postgres.dump

exit 0
加入 crontab 排程內,每天凌晨3:30做備份
30 3 * * * user sh /home/user/backupdb.sh
若要將 tar 打包好的備份檔案解壓縮,指令如下
tar -zxv -f postgres.20140924.tar.gz

2014年8月28日 星期四

【Node.js】Send Email

需求為寄出帳號認證信件
開發環境為 ubuntu, nodejs, express, smtp server
以及需要安裝兩個 nodejs 模組
nodemailer 與 nodemailer-smtp-transport
使用 npm 安裝
  1. npm install nodemailer
  2. npm install nodemailer-smtp-transport
module.exports = {
 sendEmail: function(_recipient, _subject, _html, _callback) {
  var nodemailer = require('nodemailer');
  var smtpTransport = require('nodemailer-smtp-transport');
  var config = require("../config/config");
     var transporter = nodemailer.createTransport(smtpTransport({
         host: config.smtp.host,
         port: config.smtp.port,
         auth: {
             user: config.smtp.user,
             pass: config.smtp.pwd
         }
     }));

     transporter.sendMail({
         from: 'sender@domain.org.tw',
         to: _recipient,
         subject: _subject,
         html: _html
     }, function(err, info) {
         _callback(err, info);
     });
 }
}
使用 SMTP Server 的好處是
寄件人的位置可以自行定義
若不介意寄件人地址
也可以請 Gmail 幫忙寄信
更改 transporter 即可
var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'sender@gmail.com',
        pass: 'password'
    }
});

2014年8月20日 星期三

【Ubuntu】設定開機後啟動服務

用 forever 監控 nodejs 服務
但是當 ubuntu 重啟後
forever 並不會重啟原本監控中的服務
導致監控中的 nodejs 服務中斷
因此編輯 shell script 設定 ubuntu 重啟後
forever 重新監控 nodejs 服務

在 ubuntu 路徑 /etc/init.d 下,
增加 run_forever.sh
************檔案內容開始************

forever start /var/nodejs/app.js

************檔案內容結束************

編輯完 shell script 後
還需要執行以下兩個指令

  1. sudo update-rc.d run_forever.sh defaults 99 1
  2. sudo chmod +x /etc/init.d/run_forever.sh*

最後重開機做測試,重開機指令
sudo reboot
重啟 ubuntu 之後,可用 forever list 指令觀察 nodejs 是否有執行服務

2014年6月27日 星期五

【Apache2 in Ubuntu】Host a node.js site through apache

目的:在單一 ip 上的相同 port 運行 apache 與 nodejs 服務
之所以會那麼麻煩,是因為 Apache2 in Ubuntu 所在的 ip 位置
對外服務只開放 80 port
所以才想要在單一 port 上 run apache2 與 node.js
步驟如下:
  1. install mod_proxy and mod_proxy_http
  2. update apache2 conf
  3. run node.js app
  4. restart apache2 service
  • install mod_proxy
    1. sudo apt-get install libapache2-mod-proxy-html
    2. apt-get install libxml2-dev
    3. a2enmod proxy proxy_http

  • update apache2 conf
    1. vi /etc/apache2/site-available/000-default.conf
    2. 編輯 conf 檔案,加入以下數行 code
    3. <Virtual *:80>
          ProxyRequests off
       
          <Proxy *>
              Order deny,allow
              Allow from all
          </Proxy*>
       
          ProxyPass /api http://localhost:2368
          ProxyPassReverse /api http://localhost:2368
      </Virtual>
      

  • run node.js app
    1. app.js 程式碼如下:
    2. var express = require('express');
      var app = express();
      app.get('/', function(req, res) {
          res.send("Welcome nodejs and express app api");    
      });
      app.listen(2368);
      
    3. forever start app.js(須先安裝 forever 套件)

  • restart apache2 service
    1. service apache2 reload
    2. service apache2 restart
重啟 apache 服務後
這樣連線 www.servername.com.tw 就會連到 apache index.html
而連線 www.servername.com.tw/api 則 apache 會將 request 導向 nodejs 服務
這個方法可以保持 80 port 對外,但 /api 則可以送出 request 至 node.js 監聽的 port

2014年4月15日 星期二

【jQuery】Remove item from json array

var jsonArray = [
    {name: 'Alice', id: 001},
    {name: 'Bob', id: 002},
    {name: 'Namei', id: 003}
];

假設想刪除 jsonArray 其中一個 json 物件, 該如何實作?

function findAndRemove(array, property, value) {
    for (var key in array) {
        if (array[key][property] == value) {
            array.splice(key, 1);
        }
    }
}
/* remove a json object with property of 'name' whose value is 'Namei' */
findAndRemove(jsonArray, 'name', 'Namei');

splice 為 JavaScript Array 的一個 Method
定義為: The splice() method adds/removes items to/from an array, and returns the removed item(s).
Add's Parameter: array.splice(index, howmany, item1, ....., itemX)
index 指定插入元素於陣列的位置; howmany 插入多少元素; item 為插入元素
Remove's Parameter: array.splice(index, howmany)
index 若為負值,則表示距離陣列尾端的位置; howmany: If set to 0, no items will be removed.