文章加密

;

2020年1月31日 星期五

沒有package.json怎麼辦

如果實驗安裝測試到一半,突然發現沒有這隻檔案,npm init就會出現,並且之前安裝的檔案都會寫入其中

2020年1月30日 星期四

environmenrt variables --npm package: dotenv,用來帶入.env裡的參數

https://medium.com/the-node-js-collection/making-your-node-js-work-everywhere-with-environment-variables-2da8cdf6e786

dotenv 是將 .env 文件中的環境參數加載到 process.env。這個檔要建立在最外層資料夾,在其他文件中先引入 require('dotenv').config() 後只要再呼叫 PROCESS.ENV.[變數名稱] 就能將此環境參數撈出來了,通常還會搭配 joi 來做設定,此外這邊要注意的是 .env 檔是特有的隱藏檔並不會被同步上傳傳到 GitHub 上,這樣每次 clon 下來都要手動建立一個新的檔案很麻煩,所以我都會額外建立一個叫 .example.env 的副本,每次 clone 下來直接在終端機鍵入 cp .example.env .env, cp 是 Linux 複製檔案的指令(copy),那行指令的意思是將複製一個 .example.env 檔案並且命名為 .env

2020年1月14日 星期二

node.js, middleware, express.js

https://www.nodebeginner.org/index-zh-tw.html 程度是一般入門到進階入門

解釋require("child_process").exec; https://carlos-studio.com/2017/09/04/node-js-%E4%BD%BF%E7%94%A8-child_process-%E6%A8%A1%E7%B5%84%E5%BB%BA%E7%AB%8B%E5%AD%90%E8%99%95%E7%90%86%E7%A8%8B%E5%BA%8F/  

解釋 formidable  是nodejs文件上传处理模块

重點:取得所有來自請求的資料,然後將這些資料給應用層處理,應該是HTTP伺服器要做的事情


res.setHeader('Content-Type', 'text/plain');  //表示單純的文字
res.setHeader('Content-Type', 'text/html');  //表示解讀為html


https://www.youtube.com/watch?v=vQ4KV07bVk0  nodeJS框架express快速教學
https://developer.mozilla.org/zh-TW/docs/Learn/Server-side/Express_Nodejs/Introduction  說明express--   Express的程式碼長(未看)

解釋 middleware :
// ...
public class Startup { // ... public void Configure(IApplicationBuilder app) { app.Use(async (context, next) => { await context.Response.WriteAsync("First Middleware in. \r\n"); await next.Invoke(); await context.Response.WriteAsync("First Middleware out. \r\n"); }); app.Use(async (context, next) => { await context.Response.WriteAsync("Second Middleware in. \r\n"); await next.Invoke(); await context.Response.WriteAsync("Second Middleware out. \r\n"); }); app.Use(async (context, next) => { await context.Response.WriteAsync("Third Middleware in. \r\n"); await next.Invoke(); await context.Response.WriteAsync("Third Middleware out. \r\n"); }); app.Run(async (context) => { await context.Response.WriteAsync("Hello World! \r\n"); }); } }
[鐵人賽 Day03] ASP.NET Core 2 系列 - Middleware
https://ithelp.ithome.com.tw/articles/10192682

例: Express itself is a module, as are the middleware and database libraries that we use in our Express applications.


解釋 HTTP verbs : 即HTTP request methods,常見的像是post(), get(), patch(),少見的如unlock(), report(), mkactivity(), checkout(), merge()...

解釋:What is the difference between res.end() and res.send()? 
https://stackoverflow.com/questions/29555290/what-is-the-difference-between-res-end-and-res-send  其中,比較喜歡第二個解答(Patch92說的)

解釋:next('route') 與 return next('router') 差異?
https://expressjs.com/en/guide/using-middleware.html  不懂!!0120
似乎next('route')用在http verbs如router.get, app.get
next('router')用在router.use
To skip the rest of the middleware functions from a router middleware stack, call next('route') to pass control to the next route.
NOTE:next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.

To skip the rest of the router’s middleware functions, call next('router') to pass control back out of the router instance.
就搞不清楚next的移動...
https://ithelp.ithome.com.tw/articles/10202754  先看看這篇吧


template engine like Pug, Mustache, and EJS, 即為了更好寫html而出現的程式
view engine



如何處理 404 回應?

在 Express 中,404 回應並不是錯誤的結果,因此錯誤處理常式中介軟體不會擷取它們。會有此行為是因為 404 回應僅表示沒有額外的工作來執行;換句話說,Express 已執行所有的中介軟體函數和路由,並發現它們都沒有回應。您唯一要做的是在堆疊的最底端(其他所有函數下方),新增一個中介軟體函數,以處理 404 回應:


app.use(function(req, res, next) {
  res.status(404).send('Sorry cant find that!');
});



如何呈現一般 HTML?

不需要!不需要用 res.render() 函數來「呈現」HTML。如果您有特定的檔案,請使用 res.sendFile() 函數。如果您會從目錄提供許多資產,請使用 express.static() 中介軟體函數。

express.static() 以 serve-static 為基礎,使用方法請參閱說明文件:https://github.com/expressjs/serve-static






What are “signed” cookies in connect/expressjs?



The cookie will still be visible, but it has a signature, so it can detect if the client modified the cookie.
It works by creating a HMAC of the value (current cookie), and base64 encoded it. When the cookie gets read, it recalculates the signature and makes sure that it matches the signature attached to it.
If it does not match, then it will give an error.
If you want to hide the contents of the cookie as well, you should encrypt it instead (or just stores it in the server side session). I'm not sure if there is middleware for that already out there or not.
Edit
And to create a signed cookie you would use
res.cookie('name', 'value', {signed: true})
And to access a signed cookie use the signedCookies object of req:

req.signedCookies['name']
Node - Cookie and Session

https://cythilya.github.io/2015/08/18/node-cookie-and-session/  加入credential.js 存放憑證,記得加到.gitignore使不受版控管制。


Set view engine

只能設定一種
app.set("view engine", "pug");


沒有設定的可以直接寫出副檔名仍可讀取



res.render("layout"); // 其副檔名必須為 .pug 才可以正常執行程式
res.render("regular.ntl"); // 因為有寫副檔名,雖然設定view engine為pug,但程式仍可讀取
注意!此處的ntl是自己創造出來的view engine,創造程式如下:

app.engine("ntl", function(filePath, options, callback) {
// define the template engine
fs.readFile(filePath, function(err, content) {
if (err) return callback(new Error(err));
// this is an extremely simple template engine
var rendered = content
.toString()
.replace("#title#", "" + options.title + "")
.replace("#message#", "" + options.message + "");
return callback(null, rendered);
});
});


error handler

synchronously:throw new Error('Broken')
asynchronously:next(err),
但並不是所有的asynchronously都有帶error參數,此時可用try...catch(err), Promise.resolve().then.catch(next)。
參數只有error時可以只用next

#stderr: abbreviation of standard error, 大概是“命令字元列的錯誤訊息”的意思


"debug" package

DEBUG=*,-worker:a node index.js (,之後不能有空格,否則會變認為其他package,結果會變成command not found)


Stderr vs Stdout
https://ithelp.ithome.com.tw/articles/10186972
DEBUG=app:* node index.js > stdout.txt 2> stderr.txt
>:把stdout寫入檔案
2>:把stderr寫入檔案
>>取代>:不覆蓋掉檔案、繼續寫入

#如果單純只想把stderr移除掉,免得看得很煩,可以用 2> /dev/null


Stdin vs Stdout
https://blog.xuite.net/tzeng015/twblog/113272122-UNIX+%E6%96%87%E5%AD%97%E5%B7%A5%E5%85%B7%3A+stdout+%E5%92%8C+stdin

現在我們要定義兩個術語:stdout 和 stdin。所謂一個工具軟體支援資料流流出,真正的術語是,這個工具軟體將資料輸出到【標準輸出設備】上,簡記做 stdout (standard output device)。所謂一個工具軟體支援資料流流入,真正的術語是,這個工具軟體將資料輸出到【標準輸入設備】上,簡記做 stdin (standard input device)。

  • >   >!   >> 就是將 stdout 導向至檔案
  • < 就是將檔案導向至 stdin
  • 沒有導向的時候,stdout 就是終端機的螢幕
  • 沒有導向的時候,stdin 就是終端機的鍵盤
  • 大部分濾器可以指定一個檔案給它去讀,也可以不指定。如果不指定,就自動從 stdin 取得資料。但有些濾器只能從 stdin 取得資料。例如 cat 屬於前者,tr 屬於後者 (以後會說)。


#TTY:
tty一詞源於Teletypes,或者teletypewriters,原來指的是電傳打字機,是通過串行線用打印機鍵盤通過閱讀和發送信息的東西,後來這東西被鍵盤與顯示器取代,所以現在叫終端比較合適。
終端是一種字符型設備,它有多種類型,通常使用tty來簡稱各種類型的終端設備。
大概是現在所稱的命令字元列。

#What is buffer?
https://www.runoob.com/nodejs/nodejs-buffer.html
most popular Express middleware: 未看
https://blog.jscrambler.com/setting-up-5-useful-middlewares-for-an-express-api/