Node.js/基本範例程式

出自福留子孫
跳轉到: 導覽搜尋

一、範例一

DS218+ /web 下,執行「node index.js」會出

Hello, World!
Server running at http://localhost:3000/

index.js 程式碼如下:

// 引入 Node.js 的核心模組
const http = require('http');

// 建立一個 HTTP 伺服器
const server = http.createServer((req, res) => {
  // 設定 HTTP 回應的狀態碼、標頭和內容
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!\n');
});

// 啟動伺服器,並監聽 3000 port 的連線
server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/'); // 當伺服器啟動後,在命令列中印出訊息
});

// 引入內建的 `console` 模組
const console = require('console');

// 呼叫 `console.log` 方法,在終端機中輸出一段文字
console.log('Hello, World!');

示範二

伺服器端的 js 程式透過 node.js 聽本機的 8080 port
javascript 代碼如下:

// 引入 http 模組
const http = require('http');

// 設定伺服器監聽的 port
const port = 8080;

// 建立一個 http 伺服器
const server = http.createServer((req, res) => {
  // 設定回應頭
  res.writeHead(200, {'Content-Type': 'text/html'});

  // 回應一個簡單的 HTML 頁面
  res.end(`
    <html>
      <head>
        <title>Hello World</title>
      </head>
      <body>
        <h1>Hello World!</h1>
      </body>
    </html>
  `);
});

// 監聽本機的 8080 port
server.listen(port, () => {
  console.log(`Server is listening on port ${port}`);
});

示範三

伺服器端的 js 程式透過 node.js 聽本機的 8080 port+載入另一個 javascript
javascript 代碼如下:

// 引入 http 和 fs 模組
const http = require('http');
const fs = require('fs');

// 設定伺服器監聽的 port
const port = 8080;

// 建立一個 http 伺服器
const server = http.createServer((req, res) => {
  // 如果客戶端請求的是指定的 JS 檔案,就回傳檔案內容
  if (req.url === '/myScript.js') {
    // 讀取指定的檔案
    fs.readFile('./myScript.js', (err, data) => {
      if (err) {
        // 如果讀取檔案失敗,回傳 500 錯誤碼
        res.writeHead(500);
        res.end();
      } else {
        // 如果讀取檔案成功,回傳檔案內容和正確的 content-type
        res.writeHead(200, {'Content-Type': 'text/javascript'});
        res.write(data);
        res.end();
      }
    });
  } else {
    // 如果客戶端請求的不是指定的 JS 檔案,回傳一個簡單的 HTML 頁面
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(`
      <html>
        <head>
          <title>Hello World</title>
        </head>
        <body>
          <h1>Hello World!</h1>
          <script src="/myScript.js"></script>
        </body>
      </html>
    `);
  }
});

// 監聽本機的 8080 port
server.listen(port, () => {
  console.log(`Server is listening on port ${port}`);
});

示範四

找出檔案的實體路徑
javascript 代碼如下:

console.log(__dirname); // 顯示當前模組的目錄名稱
console.log(process.cwd()); // 顯示當前工作目錄的路徑

示範五

如何在 node.js 載入 html 檔案?

如果你想要在瀏覽器中載入一個 Node.js 模組,你需要先將它轉換成瀏覽器可執行的 JavaScript 檔案,例如使用 Browserify 或 webpack 等打包工具將 Node.js 模組轉換為瀏覽器可執行的代碼,然後在 HTML 檔案中載入轉換後的代碼。

以下是一個使用 Browserify 轉換 Node.js 模組的示範
1.假設你有一個 Node.js 模組 mymodule.js,位於 ./src/mymodule.js 目錄下。
2.使用 npm 安裝 Browserify:npm install -g browserify
3.使用以下命令將 mymodule.js 轉換為瀏覽器可執行的代碼,並儲存到 bundle.js 檔案中:

browserify src/mymodule.js -o bundle.js

4.html中執行腳本

<html>
  <head>
    <script src="bundle.js"></script>
  </head>
  <body>
    <script>
      // 在瀏覽器中使用 mymodule 模組
      var mymodule = require('mymodule');
      console.log(mymodule.foo());
    </script>
  </body>
</html>

示範六

正式網頁服務 html 取用 node.js 模組只能引用 cdn 的 http 物件方法與屬性。(例如:node socket)

<script src="https://cdn.socket.io/4.6.1/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

示範七

  • 使用說明:利用 php 讀取 node.js 檔案,並使用者將兩個數值填入並按計算,答案將顯示於網頁上。
  • 範例程式:連結

index.php

<!DOCTYPE html>
<html>
<head>
	<title>兩數相加程式範例</title>
</head>
<body>
	<h1>兩數相加程式範例</h1>

	<!-- 建立一個表單,要求使用者輸入兩個數字 -->
	<form method="post">
		<label for="num1">請輸入第一個數字:</label>
		<input type="number" id="num1" name="num1" required><br><br>
		<label for="num2">請輸入第二個數字:</label>
		<input type="number" id="num2" name="num2" required><br><br>
		<input type="submit" value="計算">
	</form>

	<?php
	// 檢查使用者是否已經提交表單
	if(isset($_POST['num1']) && isset($_POST['num2'])) {
		$num1 = $_POST['num1'];
		$num2 = $_POST['num2'];

		// 透過 shell_exec() 函數呼叫 node.js 程式碼
		$output = shell_exec('node add.js ' . $num1 . ' ' . $num2);

		// 顯示計算結果
		echo "<br>第一數字:$num1<br>第二數字:$num2<br>加總答案:<strong>$output</strong>";
	}
	?>
</body>
</html>

add.js

// 從命令列讀取傳入的參數
const num1 = Number(process.argv[2]);
const num2 = Number(process.argv[3]);

// 執行加法運算
const sum = num1 + num2;

// 把結果回傳給 PHP 程式碼
console.log(sum);

二、共筆白板

  1. http://192.168.4.2/eBoard.html
  2. http://192.168.4.2/eBoard.js
    node eBoard.js 會跑 V8 然後被中斷

在 DS720+ 上執行:

  1. 先裝 Node.js v18
  2. 建 web 下建 node_socket 資料夾
  3. 上傳 Socket_test.js,Socket_test.html 到 node_socket 資料夾
  4. 取得 root 權限後在 node_socket 資料夾 執行「npm install express」
  5. 在伺服器執行「node Socket_test.js」時,會需要一連串的 node_modules ,從 etherpad 拷過來後,終於可以執行
  6. 在瀏覽器中跑「http://twees.info/node_socket/Socket_test.html」會動,但和後端連不起來
  7. 可見從 etherpad 拷過來的 node_modules ,並不符合本例中的需求,須帶芸伍電腦中的 node_modules 過來