Node.JS學習筆記(二)_npm套件指令簡單介紹_Express框架的使用_pug(哈巴狗)的前身jade(玉石)

 
https://nypost.com/2020/04/30/vet-warns-pugs-could-be-more-susceptible-to-getting-coronavirus/


NodeJs 時常搭配的開發框架 Express

官方網站:
https://expressjs.com/

在目錄下執行命令


npm install -g express

任一透過 npm安裝的套件

若是直接 npm install <package name>
只會在目前專案目錄下安置

但若是用npm install -g <package name>
則代表全域安裝的意思換言之,就是直接安裝在自己的電腦上,
而不單單專案資料夾。
以Windows 作業系統為例
預設會在如下路徑
C:\Users\<your-windows-username>\AppData\Roaming\npm




NPM 是 Node Package Manager 的簡稱,它是一個線上套件庫
可把其想成.net 的nuget


若要卸載Global Install的Package
則下npm uninstall -g <package-name> 即可

此時會發現
C:\Users\<your-windows-username>\AppData\Roaming\
下npm已經不見



那官方介紹的安裝方式
npm install express --save


這個安裝指令又有捨麼差異
npm install <package> --save
是指By單一專案的安裝
--save 的option意思是安裝在專案目錄下只要有先做 npm init ,
加入--save 之後就會自動把Package相關資訊安置進 package.json 中。



先來看看如果只執行
npm install <package>



npm install 執行完後,可以在 node_modules 中看到所有依賴的package。

比如像是
body-parser


或是cookie

這些都是可以單獨npm install 的 套件
express已經自動幫我們封裝統一下載了

Running npm install <package-name> 
will install that package only, and will not add the package to the dependencies list in package.json

Running npm install <package-name> --save 
will install that package only, and will add the package to the dependencies list.

有無加--save差別只在於會不會幫你添加到pckage.json相依列表中

事實上自npm5之後 可以省略--save參數
預設都會加到dependencies list當中


在做完npm install後 
要再執行npm init 將專案進行初始化





這裡我先寫一個測試express的小程式

剛剛命名的index.js

1
2
3
4
5
6
7
var express = require('express');

var app = express();

app.listen(3000,function(){
	console.log('Listening on port 3000');
})

執行它就會開始server程式的常駐
node {js檔案}.js


這裡我們要再裝額外的套件
就要自己到package.json引入
目前的json只有引入express套件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{
  "name": "express_app1",
  "version": "1.0.0",
  "description": "express test",
  "main": "index.js",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "ky",
  "license": "ISC"
}

編寫額外套件名稱到相依性區塊

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
{
  "name": "express_app1",
  "version": "1.0.0",
  "description": "express test",
  "main": "index.js",
  "dependencies": {
    "express": "^4.17.1",
    "body-parser": "*",
    "pug": "*",
    "nodemailer": "*"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "ky",
  "license": "ISC"
}

存檔後再次執行npm install



這樣就是套件都完成配置並無錯誤的顯示
有錯誤的顯示會長這樣(有紅色且vulnerabilities數量非0)

成功引入了後就要來載入各個套件
require 把相關的東西import到js檔案中

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));



app.listen(3000);
console.log('Server is running on port 3000...');


我們希望能夠用一個導入到HomePage的Route
出現了Cannot Get的資訊....
原因在於尚未創建對應網站跟目錄HomePage的route
這裡補上打印Hello world字串訊息的程式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.get('/', function(req, res){
	res.send('<h1>Hello World</h1>');
});

app.listen(3000);
console.log('Server is running on port 3000...');


就可以正常打印出文字資訊



上述我們透過node.js 可以簡單創建出一個web server


使用 express_generator 來迅速建立網頁

指令:
npm install -g express-generator

產生網頁對應框架子目錄
express sample1 
(可以看到express指令預設就幫我們建好package.json所以待會不需要再多一步npm init)





移動到該目錄下方
cd sample1

進行相依的package安裝
(由於sampl1子目錄自動生成的package.json檔案紀載有相依的module需要安裝)
npm install

讓node.js去執行node ./bin/www打開網頁server
npm start
此段指令是預設於package.json中會幫我們自然產生
定義在scipts中




從上面cmd輸出可知道,node進入的點是./bin/www這個檔案,


www檔案中定義了網址的port為3000,並產生http server
www檔案預設產生的程式內容

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('sample1:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}


網頁模板(jade/pug)
由於以前比較大宗在寫的 html語法 需要起始跟結尾符號寫起來較負責
因此產生類似像jade(pug)的網頁模板技術
往後只要定義起始符號即可

可以看到在express 預設產生的Views下目錄
並非我們常見的.html檔案而是.jade (有時候會看到是.pug 看express版本
是否比較新版或有指定用哪種網頁模板)

事實上預設若直接透過express產生網站目錄會發現
預設是幫我們搭配jade的模板引擎
而其實不只jade(pug) 在express指令一開始其實就能夠透過-v 來指定特定的template









Express框架預設用的就是Jade(更名為Pug)
聽說好像後來是因為jade套件本身名稱有商標重複問題所以才改成pug
詳情在網站上有提到


在網頁上呈現出來仍會是正常的html樣子

如果是原本專案有現成的html (或前端工程師寫好提供的格式較大宗是html)
bootstrap 一些範本也都html的示範跟樣板
懶得話線上也有htmltojade的工具網頁

因為一般可能在畫面設計上仍比較習慣html檔案
或者也可到codepen上做即時畫面呈現








以上是本次的筆記分享

Ref:

利用NPM快速建置Node.js網路應用框架
Node.js Express 筆記


Node.JS - 30 天入門學習筆記系列-Day12 - Express.js 簡介及安裝


Getting started with jade


《CodePen》開啟瀏覽器就可開發網頁與即使預覽(jade、SCSS、jQuery)

JADE LANGUAGE Node Template Engine

webpack3零基礎入門教程#11如何使用pug(jade)作為HTML的模板

聯成電腦網頁設計教學:HTML網頁快速產生器-淺談jade(pug)

Pug(Jade) 3.0.0 釋出,優雅強大的 Node.js 模板引擎




'Express' is not recognized command (windows)

What is the --save option for npm install?


Is npm install the same as npm install --save? [duplicate]

Uninstalling npm packages


留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題