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.

2014年4月7日 星期一

【CSS】:nth-child v.s. jQuery:eq

之前沒研究清楚,
誤以為 CSS's :nth-child  跟 jQuery's :eq
兩者的 selector 是相同效果,
但其實這兩者之間定義不完全相同。

先來看看 jQuery's :eq( index ) 的定義,
Reduce the set of matched elements to the one at the specified index.
如果 index 為正值,則是以 0 對映到首個element;
   index 為負值,則從最後一個element計數。

再來看看 CSS's :nth-child( n ) 的定義,
The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent.
n can be a number, a keyword, or a formula.
差異在於 CSS 會先找其parent的所有child element,再判斷是否符合條件。

舉例而言:
<div>
    <p>This is a heading</p>
    <div id="one" class="foo"></div>
    <div id="two" class="foo"></div>
    <div id="three" class="foo"></div>
</div>
以CSS Syntax來講, .foo:nth-child(2) 會找到 div#one ,
因為 #one 是容器內第二個元素,類別也符合條件。
但若 .foo:nth-child(1) 則找不到符合的元素,
因為容器內第一個元素是 p tag ,但卻不符合類別的條件。
補充 jQuery's :nth-child 定義,
Selects all elements that are the nth-child of their parent.
另外 jQuery's implementation of :nth- selectors is strictly derived from the CSS specification
所以 jQuery's :eq 只回傳第一個符合條件的元素;
而 jQuery's :nth-child 則會回傳所有符合條件的元素。

2014年1月16日 星期四

【Javascript】Array sort() Method

  1. 內建 Array sort
  2. var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.sort();
    // output is Apple,Banana,Mango,Orange
    
  3. 內建 reverse
  4. var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.sort();
    fruits.reverse();
    // output is Orange,Mango,Banana,Apple
    
  5. Sort numbers (numerically and ascending)
  6. var points = [40,100,1,5,25,10];
    points.sort(function(a,b){return a-b});
    // output is 1,5,10,25,40,100
    
  7. Sort numbers (alphabetically and descending)
  8. var points = [40,100,1,5,25,10];
    points.sort(function(a,b){return b-a});
    // output is 100,40,25,10,5,1
    
    ##### 上述例子為 w3shools Example #####
    ##### 以下是 object sort method #####

  9. object sort numbers
  10. var student = [{name: "Tom", score: 80}
    , {name: "Mary", score: 70}
    , {name: "Cathy", score: 90}];
    student.sort(function(a,b){return a.score-b.score});
    // output is [{name: "Mary", score: 70}, 
    // {name: "Tom", score: 80}, 
    // {name: "Cathy", score: 90}]
    
  11. object sort alphabetically
  12. var student = [{name: "Tom", score: 80}
    , {name: "Mary", score: 70}
    , {name: "Cathy", score: 90}];
    student.sort(function(a,b){return a.name > b.name});
    // output is [{name: "Cathy", score: 90}, 
    // {name: "Mary", score: 70},
    // {name: "Tom", score: 80}]