2012年5月31日 星期四

使用原生的http request進行post form呼叫

使用原生的http request進行post form呼叫:

var qs = require('querystring');
var http = require('http');

// Base authentication
var username = 'your_username';
var password = 'your_password';
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');

// The connection parameters
var opts = {
 host:"your.server.ip.address",
 port: 80,
 method: 'POST',
 path: "/your_path",
 headers :
  {
    "Authorization": auth ,
    "Content-Type":"application/x-www-form-urlencoded; charset=utf-8",
    "Content-Length": 0
  }
};

// Example function
exports.your_function = function(param1, ..., callback){
  // Process your business logic for params...
  // The post form parameters
  var form_params = {
    field1 : "value 1",
    field2 : "value 2",
    ...
  };

  var params = qs.stringify(form_params);
  opts.headers['Content-Length'] = params.length;

  var req = http.request(opts, function(res){
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
  });

  req.on('response', function(res){
    res.body = '';
    res.setEncoding('utf-8');
    res.on('data', function (chunk) {
      res.body += chunk;
    });
    
    // Trigger the callback
    res.on('end', function(){
      callback(res.body, res);
    });
  });

  req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
  });

  // write data to request body
  req.write(params);
  req.write('data\n');
  req.end();
}

// Usage of sample function
this.your_function(
    param1, ..., 
    function(body, res){
      console.log(body);
      console.log('>>>>>>>>>>>'+res.headers['Content-Type']);
    }
);

使用request套件進行http post request

使用request套件進行http post request,範例中始用到HTTP Base Authentication,如無需要,可移除Headers中的Authorization部分敘述:

1. 安裝request套件
npm install request

2. 範例執行檔案
var request = require('request');
var qs = require('querystring');

// Base Authentication
var username = 'yourname';
var password = 'yourpasswd';
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');

// Base url of you will request (include protocol, address, port, path and the lastest of '?')

// Your form fields 
var params = {
  field_A : "value a",
  field_B : "value b",
  headers: { "Authorization": auth }
}

// Append query string to your url
url += qs.stringify(params);

// Your customize function
exports.your_function1 = function(param1,..., callback) {
  //process params...
  request.post(url, params, function (e, r, body) {
      if(callback)
        callback(e, r, body);
  });
}

// Usage of your customize function:
this.your_function1(param1, ..., function(e,r,body) {
  //Process your responses
  //ex:
  console.log(body);
  console.log(r.headers['Content-Type']);
});

2012年5月7日 星期一

The Smallest Web Server Demo

Node.js官網上常常掛著Node.js的Simplest Web Server Demo
這邊把它修改一下,頁面加上顯示IP資訊
方便做為雲端多主機部署程式時檢查之用

var http = require('http');
var os = require('os');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('My Address: '+JSON.stringify(os.networkInterfaces().net0[0].address));
}).listen(1337);
console.log('Server running at http://127.0.0.1:1337/');

連線時,只要瀏覽器列打上 http://your_ip_address:1337
就可以看到如下圖的資訊



其中network interface的顯示依平台與設定而不同,在Mac上顯示資訊如下:

{ lo0: 
   [ { address: 'fe80::1', family: 'IPv6', internal: true },
     { address: '127.0.0.1', family: 'IPv4', internal: true },
     { address: '::1', family: 'IPv6', internal: true } ],
  en0: 
   [ { address: 'fe80::1240:f3ff:fe8b:a9bc',
       family: 'IPv6',
       internal: false },
     { address: '192.168.1.106', family: 'IPv4', internal: false } ] }

而筆者的另一個平台顯示如下:

 [root@simon001 ~/TestPrj]# node
> var os = require('os');
> os.networkInterfaces()
{ lo0: 
   [ { address: '127.0.0.1',
       family: 'IPv4',
       internal: true },
     { address: '::1',
       family: 'IPv6',
       internal: true } ],
  net0: 
   [ { address: '211.78.255.31',
       family: 'IPv4',
       internal: false } ] }

因此,如果要實作不同平台的程式,可要注意這些差異喲∼ 

2012年5月3日 星期四

Node.js using prototype

雖然跟prototype不熟,不過知道他是JavaScript中重要的角色
Node.js可以直接使用喔∼
下面是一個範例,提供讓string物件直接有endsWith的function...
您可以直接放在程式碼中,或是放到library裡面再require進來

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

使用方法: 直接在string物件的後面.endsWith就可以摟∼

var str = 'abc123';
if(str.endsWith('123')) {
  console.log('Yes, endsWith "123"!');
}

Node.js send mail example

無法查看此摘要。請 按這裡查看文章。

2012年5月1日 星期二

Node.js for loop...

Node.js的基本語法也繼承了javascript的寫作方法
下面展示一些for的寫作方式

第一種是基本型拉,但是值得注意的是在宣告i的時候,可以給定var變數宣告,也可以直接不要用
for ( i=0 ; i < 5 ; i++ ){
  console.log(i);
}

結果
$ node 003-for2.js 
0
1
2
3
4


第二種是將array的遞增(取出來的不是array的值,而是順序)直接指派給i變數,然後在for裡面取出i來
for ( i in process.argv ){
  console.log('-->' + i + '=' + process.argv[i]);
}

結果:
$ node 003-for.js a b c d e
-->0=node
-->1=/Users/simonsu/Workspaces/NodeWS/Sample/003-for.js
-->2=a
-->3=b
-->4=c
-->5=d
-->6=e

另外,也可以直接針對array使用forEach的方式遞迴
var aa = [1,2,3,4,5];
aa.forEach(function(t){
  console.log('>'+t);
})

上面forEach其實是array物件的一個function
而這個function接受一個callback物件的傳入
我門可以透過callback取出每一次遞回的array主體中的一個值
然後再進行處理...
也因為接受callback
某些情況我們可以把callback抽離出來,改成這樣:

var aa = [1,2,3,4,5];
var callback = function(i) {
  console.log('>'+i);
}
aa.forEach(callback);

執行結果:
$ node 003-forEach.js 
>1
>2
>3
>4
>5