
- Node.js 教程
- Node.js - 首頁
- Node.js - 簡介
- Node.js - 環境設定
- Node.js - 第一個應用程式
- Node.js - REPL 終端
- Node.js - 命令列選項
- Node.js - 包管理器 (NPM)
- Node.js - 回撥函式概念
- Node.js - 上傳檔案
- Node.js - 傳送郵件
- Node.js - 事件
- Node.js - 事件迴圈
- Node.js - 事件發射器
- Node.js - 偵錯程式
- Node.js - 全域性物件
- Node.js - 控制檯
- Node.js - 程序
- Node.js - 應用程式擴充套件
- Node.js - 打包
- Node.js - Express 框架
- Node.js - RESTful API
- Node.js - 緩衝區
- Node.js - 流
- Node.js - 檔案系統
- Node.js MySQL
- Node.js - MySQL 入門
- Node.js - MySQL 建立資料庫
- Node.js - MySQL 建立表
- Node.js - MySQL 插入資料
- Node.js - MySQL 查詢資料
- Node.js - MySQL WHERE 子句
- Node.js - MySQL ORDER BY 子句
- Node.js - MySQL 刪除資料
- Node.js - MySQL 更新資料
- Node.js - MySQL JOIN 操作
- Node.js MongoDB
- Node.js - MongoDB 入門
- Node.js - MongoDB 建立資料庫
- Node.js - MongoDB 建立集合
- Node.js - MongoDB 插入資料
- Node.js - MongoDB 查詢資料
- Node.js - MongoDB 查詢
- Node.js - MongoDB 排序
- Node.js - MongoDB 刪除資料
- Node.js - MongoDB 更新資料
- Node.js - MongoDB 限制
- Node.js - MongoDB JOIN 操作
- Node.js 模組
- Node.js - 模組
- Node.js - 內建模組
- Node.js - 實用程式模組
- Node.js - Web 模組
- Node.js 有用資源
- Node.js - 快速指南
- Node.js - 有用資源
- Node.js - 討論
Node.js - 命令列選項
任何 JavaScript 檔案(副檔名為 .js)都可以使用它作為 node 可執行檔案的命令列選項從命令提示符執行。
PS D:\nodejs> node hello.js
您可以透過執行 node 而不帶任何選項來呼叫 Node.js REPL。
PS D:\nodejs> node >
此外,node 命令列中可以使用許多選項。要獲取可用的命令列選項,請使用 --help
PS D:\nodejs> node --help
一些常用的命令列選項(有時也稱為開關)如下所示:
顯示版本
PS D:\nodejs> node -v v20.9.0 PS D:\nodejs> node --version v20.9.0
評估指令碼
PS D:\nodejs> node --eval "console.log(123)" 123 PS D:\nodejs> node -e "console.log(123)" 123
顯示幫助
PS D:\nodejs> node -h PS D:\nodejs> node –help
啟動 REPL
PS D:\nodejs> node -i PS D:\nodejs> node –interactive
載入模組
PS D:\nodejs> node -r "http" PS D:\nodejs> node –require "http"
您可以將引數傳遞給要從命令列執行的指令碼。這些引數儲存在一個數組 process.argv 中。陣列中的第 0 個元素是 nide 可執行檔案,第一個元素是 javascript 檔案,後面是傳遞的引數。
將以下指令碼儲存為 hello.js 並從命令列執行它,從命令列向其傳遞字串引數。
const args = process.argv; console.log(args); const name = args[2]; console.log("Hello,", name);
在終端中輸入
PS D:\nodejs> node hello.js TutorialsPoint [ 'C:\\nodejs\\node.exe', 'D:\\nodejs\\a.js', 'TutorialsPoint' ] Hello, TutorialsPoint
您還可以從 Node.js 的命令列接受輸入。從 Node.js 7 版本開始,為此提供 readline 模組。createInterface() 方法有助於從可讀流(例如 process.stdin 流)設定輸入,在 Node.js 程式執行期間,該流是終端輸入,一次一行。
將以下程式碼儲存為 hello.js
const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout, }); readline.question(`What's your name?`, name => { console.log(`Hi ${name}!`); readline.close(); });
question() 方法顯示第一個引數(一個問題)並等待使用者輸入。按下 Enter 鍵後,它會呼叫回撥函式。
從命令列執行。Node 執行時等待使用者輸入,然後在控制檯上回顯輸出。
PS D:\nodejs> node a.js What's your name?TutorialsPoint Hi TutorialsPoint!
您還可以從命令列設定環境變數。在 node 可執行檔名之前為一個或多個變數賦值。
USER_ID=101 USER_NAME=admin node app.js
在指令碼中,環境變數作為 process.env 物件的屬性可用。
process.env.USER_ID; // "101" process.env.USER_NAME; // "admin"
廣告