顯示具有 basic 標籤的文章。 顯示所有文章
顯示具有 basic 標籤的文章。 顯示所有文章

2013年2月6日 星期三

Call by value and call by reference of Node.js

Node.js中的變數,屬於call by value的範圍(我猜是原生型別的關係)
下面是範例:

var a = 1;
var b = a;
console.log(a + '::' + b);
> 1::1
b = b + 1;
console.log(a + '::' + b);
> 1::2

上面的b值改變時候,不影響a值,因此a與b無reference關係...

而物件的話,看起來屬於call by reference...

var a = {aa: 111};
var b = a;
console.log(a);
console.log(b);
console.log('===========');
b.aa = 222;
console.log(a);
console.log(b);
>{ aa: 111 }
>{ aa: 111 }
>============
>{ aa: 222 }  //這是a
>{ aa: 222 }  //這是b

上面的b物件改變aa的值時候,實際上影響到a物件的aa值,屬於call by reference
因此在操作時候需要特別小心...
一個不小心....!@#!$!@#


2013年1月19日 星期六

String as a Function

寫程式的時候,常會有需要從原始碼直接執行的需要
例如,需要把程式碼片段藏在DB中,依照不同的需求取出不同的程式碼來執行
這時候就非常需要能夠從文字重組回物件的方式
在Java裡面,是透過Class.forName(className)的方式,從原始碼中創建一個類別來執行
在Node.js中,有著JavaScript的許多特性
其中一個好用的funciton:eval(),可幫助執行一個純文字輸入的javascript片段
範例:

/tmp/fn.txt
{
  "name":"test",
  "fn":"fn = function(v){ console.log('Hello...' + v); }"
}


/tmp/test.js
var fs = require('fs')
fs.readFile('/tmp/fn.txt', 'UTF-8', function(e, d){ 
  var obj = JSON.parse(d);
  var fnc = eval(obj.fn)
  fn("test");
});

# node /tmp/test.js
Hello...test

上面範例,其中fn.txt中的fn=,測試下是必須要給定
似乎是因為eval會實際執行輸入字串中的語句
而function的語法中,如果是匿名function的話
則必須給定給一個變數
這樣也方便讓eval後的程式片段可以用一個名稱直接呼叫
如此,不論是來自file或是db的程式片段,都可以用類似方式動態載入來使用喔∼


2013年1月2日 星期三

Json to HTML Table

Json to HTML Table是擷取自afshinm的專案,目的是讓所有的Json物件可以輕易的在javascript中轉換成為Html Table的字串
當中也支援http(s)://, ftp://, file://, javascript:()等輸出的轉換,可以方便顯示json物件中的不同屬性文字...
原先開發nodeutil的目的在蒐集各種常用的套件,當中引用該模組作為Node.js中處理Json物件轉換成Html Table的功能
在撰寫Mail或是Render Web時候,可以派上用場...

用法:
var j2t = require('nodeutil').json2table;
app.get('/test', function(req, res){
  var json = [
    {Desc:'Sample of using javascript', Code:'javascript:(alert(\'TEST\'));'},
    {Desc:'Sample of using http', Code:'http://www.google.tw'},
    {Desc:'Sample of using https', Code:'https://www.google.tw'},
    {Desc:'Sample of using ftp', Code:'ftp://www.ntu.edu.tw'}
  ];
  res.end(
    j2t.ConvertJsonToTable(
      json, 
      'jsonTable', 
      'tbclass', 
      '<img src="http://cdn1.iconfinder.com/data/icons/Map-Markers-Icons-Demo-PNG/48/Map-Marker-Push-Pin--Right-Azure.png"/>'
    )
  );
}); 

其中json物件的key部分會變成table title,並且以第一列的為主要顯示,其下有未填寫的部份會補上{0}
value的部份如有http(s)://, ftp://, file://, javascript:()等開頭的文字,將會自動轉變成link輸出
而主要轉換的function是ConvertJsonToTable((objectArray, tableId, tableClass, linkReplace)),帶入四個參數:
  • objectArray: json array物件,主要輸出內容部分
  • tableId: 將帶入到輸出的table id屬性
  • tableClass: 將帶入到輸出的table class屬性
  • linkReplace: 將帶入到所有被轉換成link的顯示文字(或物件)

輸出畫面: 



輸出的HTML原始碼:
<table border="1" cellpadding="1" cellspacing="1" id="jsonTable" class="tbclass"><thead><tr><th>Desc</th><th>Code</th></tr></thead><tbody><tr><td>Sample of using javascript</td><td><a href="javascript:(alert('TEST'));"><img src="http://cdn1.iconfinder.com/data/icons/Map-Markers-Icons-Demo-PNG/48/Map-Marker-Push-Pin--Right-Azure.png"/></a></td></tr><tr><td>Sample of using http</td><td><a href="http://www.google.tw"><img src="http://cdn1.iconfinder.com/data/icons/Map-Markers-Icons-Demo-PNG/48/Map-Marker-Push-Pin--Right-Azure.png"/></a></td></tr><tr><td>Sample of using https</td><td><a href="https://www.google.tw"><img src="http://cdn1.iconfinder.com/data/icons/Map-Markers-Icons-Demo-PNG/48/Map-Marker-Push-Pin--Right-Azure.png"/></a></td></tr><tr><td>Sample of using ftp</td><td><a href="ftp://www.ntu.edu.tw"><img src="http://cdn1.iconfinder.com/data/icons/Map-Markers-Icons-Demo-PNG/48/Map-Marker-Push-Pin--Right-Azure.png"/></a></td></tr></tbody></table>




2012年12月23日 星期日

callee and caller

簡介一下callee與caller
  • callee為function arguments的一個操作,用來代表function本身
  • caller為function呼叫者,若為最上層呼叫
下面是簡單的操作,將callee與caller的值列印出來:

由fn2操作fn1,最上層呼叫直接呼叫fn2

function fn1(){
  console.log('>>fn1');
  console.log('my callee:'+arguments.callee);
  console.log('my caller:'+fn1.caller);
}
function fn2(){
  console.log('>>fn2');
  fn1();
}
fn2();

執行結果:
# node test 
>>fn2
>>fn1
my callee:function fn1(){
  console.log('>>fn1');
  console.log('my callee:'+arguments.callee);
  console.log('my caller:'+fn1.caller);
}
my caller:function fn2(){
  console.log('>>fn2');
  fn1();
}


如果想要測試最上層直接呼叫fn1的狀況,修改程式碼如下:

function fn1(){
  console.log('>>fn1');
  console.log('my callee:'+arguments.callee);
  console.log('my caller:'+fn1.caller);
}
fn1();

則結果為:
# node test
>>fn1
my callee:function fn1(){
  console.log('>>fn1');
  console.log('my callee:'+arguments.callee);
  console.log('my caller:'+fn1.caller);
}
my caller:function (exports, require, module, __filename, __dirname) { function fn1(){
  console.log('>>fn1');
  console.log('my callee:'+arguments.callee);
  console.log('my caller:'+fn1.caller);
}
fn1();

}

其中callee的應用,可以用在loop的程式中,強迫程式同步進行...
ex:
var count = 5;
process.nextTick(function fn1(){
  count --;
  console.log('>>fn1, ts=%s, count=%s', new Date().getTime(), count);
  if(count > 0) process.nextTick(arguments.callee);
});

執行結果:
# node test 
>>fn1, ts=1356282477274, count=4
>>fn1, ts=1356282477280, count=3
>>fn1, ts=1356282477281, count=2
>>fn1, ts=1356282477281, count=1
>>fn1, ts=1356282477281, count=0

這邊的output就可以看得出來function fn1會依序被執行,如果有非同步動作,則可以在callback中使用同樣手法讓程序變成循序執行的...

另外,caller的應用,直覺想到的是debug...
寫個簡單的log程式如下,希望可以記錄錯誤是由哪個function發出來的:
var log = {
  info: function fn(msg){
    console.log("Call from [%s]: %s", fn.caller.name , msg);
  }
}
function doSomething() {
  log.info('test');
}
doSomething();


執行結果:
node test
Call from [doSomething]: test



2012年11月25日 星期日

Node.js的forEach迴圈非循序進行

Node.js的forEach迴圈非循序進行:

var arr = [1,2,3,4,5,6,7]

arr.forEach(function(v,i){
  exec('echo ' + arr[i], function(err, stdo, stde){
    console.log('-->' + stdo);
  });
});

執行1:
# node test.js 
-->6
-->5
-->4
-->3
-->2
-->1
-->7

執行2:
# node test.js 
-->5
-->4
-->3
-->2
-->1
-->7
-->6

2012年7月23日 星期一

NPM using proxy

在使用NPM指令時候,如果剛好在個有Proxy的區域
常常npm會有問題,Linux的使用者會這麼做:

export HTTP_PROXY=http://your.proxy.ip.address:port

讓程是預設吃這個位置的proxy設定
但是Windows的使用者一般都是到網路管理界面設定...
這部分NPM連線就有問題
作法很簡單,Windows中的NPM也吃HTTP_RPOXY這個參數
所以只要這樣做:

set HTTP_PROXY=http://your.proxy.ip.address:port

就可以正常使用NPM了...

當然∼要確認NPM的repository是否可以辨識得到(這部分是跟DNS有關)


如果不小心被DNS漏掉,可以加到static route去(/etc/hosts或C:\Windows\system32\drivers\etc\hosts)
他的IP可以這樣查:

nslookup registry.npmjs.org 8.8.8.8

其中8.8.8.8是Google的DNS服務...將查到的IP寫到static route去就可以摟∼

2012年7月17日 星期二

JSON object in node.js

在Node.js/JavaScript中
針對JSON物件可以用這樣的方法循序倒出來

$ node
> var json = { "aa":1, "bb":2,"cc":3}
> for(key in json){
... console.log(key);
... }
aa
bb
cc
> 

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"!');
}

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




2012年4月29日 星期日

Reading local filesystem

Node.js的功能涵蓋相當完整,這邊介紹Node.js的filesystem讀取:

var fs = require('fs')
var files = fs.readdirSync('.');
for ( i in files ) {
  console.log(files[i]);
}

fs是Node.js的標準模組
相關文件可以參考:http://nodejs.org/api/fs.html
建立fs物件之後,可以使用readdirSync()來讀取某個path的列表
回傳值為該folder下面的物件(檔案、資料匣)的列表






2012年4月28日 星期六

Basic of Node.js - Non-Block

Node.js以JavaScript為語法結構,同樣繼承JavaScript的Non-Block特性,下面範例說明在Non-Block的程序中,同樣print一筆資料,順序性並非程式碼中行號的順序,而是每個程序執行的回應時間

Ex1:

setTimeout(function(){
  console.log("foo...");
}, 1000);
console.log("bar...");

結果:
$ node 000-nonblock.js
bar...
foo...

由上面結果可以看到foo程序雖然在bar程序之前,但是因為foo需要等待1000毫秒,所以會再bar程序之後印出
為了讓執行時間瞬間被列出,修改上面程式如下:

Ex2: (000-nonblock3.js)
function ffoo(){
  log('Start foo...');
  setTimeout(function(){
    log("foo...");
  }, 1000);
  log('End foo...');
}
function fbar(){
  log('Start bar...');
  log('bar...');
  log('End bar...');
}
function log(msg) {
  console.log("["+new Date()+"]"+msg);
}  
//真正執行區塊
ffoo(); //
fbar();
結果:
$ node 000-nonblock3.js
[Sun Apr 29 2012 00:44:53 GMT+0800 (CST)]Start foo...
[Sun Apr 29 2012 00:44:53 GMT+0800 (CST)]End foo...
[Sun Apr 29 2012 00:44:53 GMT+0800 (CST)]Start bar...
[Sun Apr 29 2012 00:44:53 GMT+0800 (CST)]bar...
[Sun Apr 29 2012 00:44:53 GMT+0800 (CST)]End bar...
[Sun Apr 29 2012 00:44:54 GMT+0800 (CST)]foo...
SimonAIR:Sample simonsu$ vi 000-nonblock3.js 

由上面時間可以很清楚看出ffoo()中的"Start foo..."訊息在程式一開始即已列出,接著馬上執行"End foo...",然後"Start bar..."
這意味著setTimeout function中要列印出的"foo..."被Non-Block丟出一個執行序去執行了
而該執行蓄因為要等待1000毫秒才回應,所以程序先跑下面的部分

另外關於"Start bar...", "bar...", "End bar..."部分照順序被列出來,則是非Non-Block程式碼的順序性所致

在Node.js / JavaScript的世界裡,Block與Non-Block的交互使用有不少好處,卻也會惹出不少麻煩,慎用阿!