首先用 Hyper cd 到目標的資料夾,然後創一個叫做 server.js 的檔案:
(base) wwwsss@wwwsssdeMacBook-Pro front-end_projects % cd my-express-server
(base) wwwsss@wwwsssdeMacBook-Pro my-express-server % touch server
.js
然後 initialize 這個專案。
(base) wwwsss@wwwsssdeMacBook-Pro my-express-server % npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (my-express-server)
version: (1.0.0)
description: practice server
entry point: (server.js)
test command:
git repository:
keywords:
author: ws
license: (ISC)
About to write to /my-express-server/package.json:
{
"name": "my-express-server",
"version": "1.0.0",
"description": "practice server",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "ws",
"license": "ISC"
}
Is this OK? (yes)
原本不太知道這步驟要幹嘛,所以上網查了一下:
NPM 新手教學 - J.H. Blog
npm init 這個指令,會問你一些關於專案的問題,像是專案名稱、專案的描述、專案的入口點、測試指令、git遠端儲存庫位置、專案作者... 等問題。 完成後,會在專案資料夾下建立一個package.json 檔案,這個檔案就是專案的描述檔,專案的所有資訊都會存在這裡。
接著再用 npm 安裝 express:
(base) wwwsss@wwwsssdeMacBook-Pro my-express-server % npm install
express
added 57 packages, and audited 58 packages in 5s
7 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
(base) wwwsss@wwwsssdeMacBook-Pro my-express-server % node server.
js
按照文件說的把需要 require 的功能打好:
var express = require('express');
var app = express();
app.listen(3000, function() {
console.log('Hello');
});
加一個 console.log,等等看看他在 node 執行的狀況如何。
ok,最後一步是看看用 node 是否可以執行這個 .js 檔案:
(base) wwwsss@wwwsssdeMacBook-Pro my-express-server % node server.js
Hello
當要離開這個 server 時,可以用 ctrl+C 離開。
^C