首頁  >  文章  >  web前端  >  Node.js 入門

Node.js 入門

WBOY
WBOY原創
2024-08-21 06:12:35599瀏覽

Getting Started with Node JS

什麼是 NodeJS?

  • 定義:NodeJS 是一個開源、跨平台的 JavaScript 執行時間環境,可讓您在 Web 瀏覽器之外執行 JavaScript 程式碼。
  • 用途:它主要用於伺服器端腳本,其中 JavaScript 用於在頁面發送到使用者的 Web 瀏覽器之前產生動態 Web 內容。
  • 主要特點
    • 事件驅動架構:NodeJS 使用事件驅動、非阻塞 I/O 模型,使其高效且輕量。
    • 單線程:雖然是單線程,NodeJS 使用其非同步特性和事件循環來處理並發操作。
    • 基於 V8 構建:NodeJS 基於 Google Chrome 的 V8 JavaScript 引擎構建,使其執行 JavaScript 程式碼的速度非常快。

NodeJS 如何在背景工作?

  • 事件循環

    • NodeJS 在單執行緒事件循環上運行,這使得它可以在不阻塞執行緒的情況下處理多個並發請求。
    • 事件循環的階段:
    • 定時器:執行由setTimeout()和setInterval()所安排的回呼。
    • 待處理回呼:執行延後到下一個循環迭代的 I/O 回呼。
    • 空閒,準備:由 NodeJS 內部使用。
    • Poll:檢索新的 I/O 事件並執行 I/O 相關的回呼。
    • Check:執行由setImmediate()安排的回呼。
    • 關閉回呼:執行關閉事件回呼。
  • 非阻塞 I/O:NodeJS 非同步處理 I/O 操作,這表示它不會等待操作完成就繼續下一個任務。

範例

  const fs = require('fs');

  console.log("Start");

  // Reading a file asynchronously
  fs.readFile('example.txt', 'utf8', (err, data) => {
      if (err) throw err;
      console.log(data);
  });

  console.log("End");

輸出:

  Start
  End
  (contents of example.txt)

說明

  • NodeJS 在呼叫 fs.readFile() 函數後繼續執行程式碼,而不等待檔案被讀取。這展示了它的非阻塞 I/O 模型。

NodeJS 中的模組是什麼?

  • 定義:模組是封裝的程式碼區塊,它們根據相關功能與外部應用程式進行通訊。
  • 模組類型
    • 核心模組:內建於 NodeJS(例如,fs、http、path 等)。
    • 本地模組:由使用者創建,用於組織和建構程式碼。
    • 第三方模組:透過 npm 安裝(例如,express、lodash)。

JavaScript 和 NodeJS 中導入和導出模組的方法

在 JavaScript 中(ES6 模組):

  • 導出
  // Named export
  export const add = (a, b) => a + b;

  // Default export
  export default function subtract(a, b) {
      return a - b;
  }
  • 導入
  // Named import
  import { add } from './math.js';

  // Default import
  import subtract from './math.js';

在 NodeJS(CommonJS 模組)中:

  • 導出
  // Using module.exports
  module.exports.add = (a, b) => a + b;

  // Using exports shorthand
  exports.subtract = (a, b) => a - b;
  • 導入
  // Importing modules
  const math = require('./math.js');
  const add = math.add;
  const subtract = math.subtract;

NodeJS 中的檔案處理是什麼?

  • 定義:NodeJS 中的檔案處理可讓您使用電腦上的檔案系統,包括讀取、寫入、更新和刪除檔案。

重要功能:

  • 一些最重要的 fs 模組函數
    • fs.readFile():非同步讀取檔案內容。
    • fs.writeFile():非同步將資料寫入文件,如果文件已存在則取代該文件。
    • fs.appendFile():將資料追加到檔案中。如果該檔案不存在,則會建立一個新檔案。
    • fs.unlink():刪除檔案。
    • fs.rename():重新命名檔案。

範例

  const fs = require('fs');

  // Writing to a file
  fs.writeFile('example.txt', 'Hello, NodeJS!', (err) => {
      if (err) throw err;
      console.log('File written successfully.');

      // Reading the file
      fs.readFile('example.txt', 'utf8', (err, data) => {
          if (err) throw err;
          console.log('File contents:', data);

          // Appending to the file
          fs.appendFile('example.txt', ' This is an appended text.', (err) => {
              if (err) throw err;
              console.log('File appended successfully.');

              // Renaming the file
              fs.rename('example.txt', 'newExample.txt', (err) => {
                  if (err) throw err;
                  console.log('File renamed successfully.');

                  // Deleting the file
                  fs.unlink('newExample.txt', (err) => {
                      if (err) throw err;
                      console.log('File deleted successfully.');
                  });
              });
          });
      });
  });

輸出:

  File written successfully.
  File contents: Hello, NodeJS!
  File appended successfully.
  File renamed successfully.
  File deleted successfully.

如何在 NodeJS 中建立伺服器?

  • 使用 http 模組:http 模組是 NodeJS 中的核心模組,可讓您建立伺服器來偵聽特定連接埠上的請求並傳送回應。

範例

  const http = require('http');

  // Creating a server
  const server = http.createServer((req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
      res.end('Hello, World!\n');
  });

  // Listening on port 3000
  server.listen(3000, '127.0.0.1', () => {
      console.log('Server running at http://127.0.0.1:3000/');
  });

輸出:

  Server running at http://127.0.0.1:3000/
  • Explanation: The server responds with "Hello, World!" every time it receives a request. The server listens on localhost (127.0.0.1) at port 3000.

What is an HTTP Module?

  • Definition: The http module in NodeJS provides functionalities to create HTTP servers and clients.

Important Functions?

  • Some of the most important functions of HTTP module are:
    • http.createServer(): Creates an HTTP server that listens to requests and sends responses.
    • req.method: Retrieves the request method (GET, POST, etc.).
    • req.url: Retrieves the URL of the request.
    • res.writeHead(): Sets the status code and headers for the response.
    • res.end(): Signals to the server that all of the response headers and body have been sent.

Example:

  const http = require('http');

  const server = http.createServer((req, res) => {
      if (req.url === '/') {
          res.writeHead(200, { 'Content-Type': 'text/plain' });
          res.end('Welcome to the homepage!\n');
      } else if (req.url === '/about') {
          res.writeHead(200, { 'Content-Type': 'text/plain' });
          res.end('Welcome to the about page!\n');
      } else {
          res.writeHead(404, { 'Content-Type': 'text/plain' });
          res.end('404 Not Found\n');
      }
  });

  server.listen(3000, '127.0.0.1', () => {
      console.log('Server running at http://127.0.0.1:3000/');
  });

Output:

  • If you navigate to http://127.0.0.1:3000/, the server will display "Welcome to the homepage!".
  • If you navigate to http://127.0.0.1:3000/about, the server will display "Welcome to the about page!".
  • If you navigate to any other URL, the server will display "404 Not Found".

以上是Node.js 入門的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn