Category Archives: nodejs

express error handler

在 https://github.com/expressjs/express/blob/master/lib/router/index.js#L46 function router(req, res, next) { router.handle(req, res, next); } express router不會catch error,所以error handler定義在router內無法作用 要直接定義在app那層,參考doc Error-handling middleware app.use(function(err, req, res, next) { console.error(err.stack); res.status(500).send(‘Something broke!’); }); 另外是順序也很重要,next(err)會依照順序往下找,因此error handler應該定義在最後面 參考來源: https://stackoverflow.com/questions/45431595/express-error-handler-inside-router-doesnt-work

Posted in nodejs | Leave a comment

js convert to number

在要轉成number型態時 可用 |0的方式 null | 0 = 0 undefined | 0 = 0 “” | 0 = 0 true | 0 = 1 false | 0 = 0 但注意 | operator有32 bit限制 如果是像 unix timestamp milliseconds的”字串” (例如從網路傳上來) 轉成number時 “1534478379792”|0 = … Continue reading

Posted in nodejs | Leave a comment

async常用function整理

concat, concatSeries 連接results in arrayeach, eachSeries 分別執行every, everySeries 分別執行並加上true/false判斷(false即返回)filter, filterSeries 分別執行並加上true/false判斷(只回傳true的coll), 與reject相反map, mapSeries 分別執行並回傳resultsreduce 分別執行並往下傳resultseries 分別執行function, 返回值統一在callback resultswaterfall 分別執行function, 返回值往下傳 實際上大概 mapSeries, waterfall比較常用到,特別像是在一個api裡要執行一連串SQL時。 waterfall則用在SQL根據上一個返回結果動態生成時方便使用 參考: https://caolan.github.io/async/docs.html

Posted in nodejs | Leave a comment

nodejs request iconv

在使用nodejs request抓取網頁時,如果需要進行轉碼,則須注意request的callback中body是string or buffer 對於Big5來說 如果轉成javascript string, 此時body在iconv(由big5=>utf8)會失敗。 javascript string假設input是utf8 需要強制body保留原始bytes request({ url: …, method: ‘GET’, encoding: null }, function (err, resp, body){ //body is buffer now }); 在說明文件有提到 encoding – encoding to be used on setEncoding of response data. … Continue reading

Posted in nodejs | Leave a comment

npm tips

# 查版本 npm –version # 查看相關環境版本 npm version { npm: ‘5.5.1’, ares: ‘1.10.1-DEV’, cldr: ‘31.0.1’, http_parser: ‘2.7.0’, icu: ‘59.1’, modules: ’57’, nghttp2: ‘1.25.0’, node: ‘8.9.1’, openssl: ‘1.0.2m’, tz: ‘2017b’, unicode: ‘9.0’, uv: ‘1.15.0’, v8: ‘6.1.534.47’, zlib: ‘1.2.11’ } #起始一個project產生package.json npm … Continue reading

Posted in nodejs | Leave a comment