Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Node.js 基礎學習筆記

Node.js 是以 C++ 開發、可執行 JavaScript 的執行環境,常用於服務器端或系統級程式。本文整理 Node.js 的模組機制、HTTP 伺服器建立、回調函數與閉包特性。

建立 HTTP 伺服器

使用 node 執行 JavaScript 檔案時,可先建立一個簡單 HTTP 伺服器並監聽指定埠。

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(80, "127.0.0.1");

當有 HTTP 請求進來時,Node.js 會呼叫 createServer 中的回調函數,由回調函數處理請求並回傳回應。

回調與閉包

Node.js 大量使用回調函數。以下範例展示如何在非同步流程中,用閉包保存並逐步組裝回應內容。

var hostRequest = http.request(requestOptions, function(response) {
  var responseHTML = '';

  response.on('data', function (chunk) {
    responseHTML = responseHTML + chunk;
  });

  response.on('end', function() {
    console.log(responseHTML);
  });
});

responseHTML 定義在回調函數外側,data 事件可修改它,end 事件則可使用最終結果,這是閉包特性的常見應用。

CommonJS 模組機制

JavaScript 早期缺少標準模組系統與相依管理,CommonJS 規範因此應運而生,Node.js 是其重要實作。Node.js 使用 require 載入模組,並以 exports 暴露方法。

var PI = Math.PI;

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};

另一個檔案可用 require 載入:

var circle = require('./xx.js');
console.log('The area of a circle of radius 4 is ' + circle.area(4));

require 為何可用

Node.js 在執行主模組前,會把檔案包裝成一個函數,並傳入 exports、require、module、__filename 與 __dirname 等參數。因此即使主檔中沒有自行定義 require,仍然可以使用。

(function (exports, require, module, __filename, __dirname) {
  var circle = require('./xx.js');
  console.log('The area of a circle of radius 4 is ' + circle.area(4));
});

require 實際上會呼叫 load 方法,載入、編譯並快取 module,最後回傳 module 的 exports 物件。這也是為什麼只有定義在 exports 上的方法才能被外部呼叫。

Copyright © Linux教程網 All Rights Reserved