Monthly Archives: October 2018

exit process with delay

在nodejs中處理error發生要結束process時,可使用process.exit,但注意process.exit會立即返回特別是當要寫error log時,有可能還沒寫完就結束process了。這種情況可以利用timer來控制這裡節錄stackoverflow上的一個解法 Exit Node.js process after event loop is empty OR after timeout 以下節錄 如果時間到 event loop不為空,仍然會執行process.exit,中斷未完成的task。當然這邊會有其他的問題,因為通常發生異常必須結束時,會希望取消其他進行中的async task,單純記上error log,但許多async api並沒有取消的方式。

Posted in nodejs | Leave a comment

expressjs send file

在 expressjs傳送檔案可以直接使用res.sendFile或是開啟readable stream再pipe到res fs.createReadStream(fpath).pipe(res) 但在某些情況(例如video播放)這樣的方式太陽春,沒辦法seek (http byte range request) 特別是例如iOS safari browser在播放mp4影片時,會要求伺服器支援byte range request,不然不會播放。Safari Web Content Guide#Configuring Your Server HTTP servers hosting media files for iOS must support byte-range requests, which iOS uses to perform random access in media playback. … Continue reading

Posted in nodejs | Leave a comment

remote deploy with ssh

遠端佈署時,常常更新完檔案要重新啟動服務,使用ssh execute remote command 可以整合在script方便automation ssh $HOST COMMANDssh $HOST COMMAND1; COMMAND2; … scp SCRIPT.sh $HOST:ssh $HOST SCRIPT.sh #將多個command 放在script 以上使用SSH Key-Based Authentication的方式驗證

Posted in System Administration | Leave a comment

moment.js

在js的程式哩,對於時間格式處理解析與驗證可以使用momentjs, 下面簡要整理 處理不同版本js的Date對於字串解析的不一致 var a = new Date(‘2016-01-01’); ES5(解成UTC), ES2015(解成local time) mutable: t.add(1, ‘days’) 這樣會直接影響到t,如果要重複操作時 t.clone().add(1, ‘days’), value可為負數 避免在操作 add傳入小數點 處理timezone相關問題時要注意DST, daylight saving time 儘量使用.format(…)顯示描述轉成字串的格式 moment.utc(), moment().utc() 可以理解成目前是UTC timezone moment距離 x.diff(y) => x減去y 回傳 milliseconds moment.duration(milliseconds number) 再用 asDays()等的function轉單位 解析時間: … Continue reading

Posted in nodejs | Leave a comment

let scope

雖然let引入block scope,避免了var的variable hoisting,但是須注意 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let let bindings are created at the top of the (block) scope containing the declaration, commonly referred to as “hoisting”. Unlike variables declared with var, which will start with the value undefined, let variables are not initialized … Continue reading

Posted in nodejs | Leave a comment

JSON5

JSON5 (https://spec.json5.org) https://github.com/json5/json5 nodejs讀取設定檔常使用json格式(http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf, https://tools.ietf.org/html/rfc8259), 但是json在描述時限制較多,例如在key要雙引號,字串要用雙引號不能用單引號,不能有註解等。 因此可讀性變差,JSON5主要將ECMAScript 5.1語法引入,整體看來,syntax對於熟悉javascript的使用者更友善 幾個比較大的差異 key不一定需要引號(根據ECMAScript 5.1 IdentifierName規則) Objects may have a single trailing comma. Arrays may have a single trailing comma. Strings may be single quoted/支援多行/支援 \x的escape (U+0000 through U+00FF) String更寬容的escape字元包含 JSON:All Unicode characters may … Continue reading

Posted in nodejs | Leave a comment