2012-04-06

NodeJS 執行時期更新程式碼

這是一個很酷的特性!nodejs 在執行期間不必重新啟動就可以更新程式碼!例如有個用 nodejs 寫的 http / socket server 正在執行當中,現在要為它修改或是增加新的功能,則直接修改程式碼後儲存,完全不必重新啟動伺服器。
底下是一個簡單的範例,把 main.js 執行起來,它會監控 module0.js ,並定時呼叫 module0.js 的 say function ,當 module0.js 更動後(例如更改 say funciton 裡要顯示出的字串),它會自動重新載入 module0.js 的程式碼:

檔案 main.js :
var l_module =require('./module0');
var l_fs =require('fs');

l_fs.watch('module0.js',
    function(event, pFilename)
    {
        console.log('new event='+event+', filename='+pFilename);
        if (event ==='change')
        {
            var name =require.resolve('./module0');
            delete require.cache[name];
            console.log('resolved modulename ='+name);
               
            try
            {
                l_module =require('./module0');               
            }
            catch(err)
            {
                console.log(err);
                l_module =undefined;
            }
        }
    }
);

var dosomething =
    function()
    {
        if (l_module !==undefined &&
            l_module.hasOwnProperty('say')===true)
        {
            l_module.say();
        }
        else
        {
            console.log('module unavailable');
        }
       
        setTimeout(dosomething, 1000);
    };
   
setTimeout( dosomething, 1000 );


檔案 module0.js :
exports.say =
    function()
    {
        console.log('im module0 -version 0');
    };

1 則留言 :

  1. Although there isn’t a dedicated app, you’ll have entry to all the features you want while betting on the go. BetOnline allows clients to select out} from a wide range|a variety} of sports markets, including futures, props, motion reverse, if bets, teasers, parlays, straight bets, and extra. This ensures that you have got} many choices to customize your bet slips and improve your winning possibilities. Perhaps the best part, it’s straightforward to entry buyer assist features, including the reliable 24/7 reside 다 파벳 우회 주소 chat. So rest assured, everytime you want some help or data, might get} it in a matter of some minutes. Ignition’s design and layout are simply out of this world, with each element placed completely to ensure you|to ensure you} have a clean on-line playing experience.

    回覆刪除