Skip to main content

node modules 常用功能

Path

當你載入 var path = require('path'); ,便可用下述語法取得檔案與目錄路徑,詳細也可瀏覽 Node.js PATH API文件

抓目錄路徑: 回傳 /xx/yy

const path = require('path')
path.dirname('/xx/yy/zz.js') 

路徑合併:回傳 前後路徑合併

path.join(__dirname,'/xx') 

抓檔名: 回傳 zz.js

path.basename('/xx/yy/zz.js') 

抓副檔名: 回傳 js

path.extname('/xx/yy/zz.js') 

分析路徑: 回傳 上述綜合物件

path.parse('/xx/yy/zz.js') 

mail template

由 node 轉 .mjml 變成 .html,在寄信。

https://github.com/mjmlio/email-templates

child_process

https://ithelp.ithome.com.tw/articles/10232335

https://medium.com/wenchin-rolls-around/node-js-%E7%9A%84%E5%AD%90%E7%A8%8B%E5%BA%8F%E6%A8%A1%E7%B5%84-child-process-196529aacfdd

util.promisify 的那些事儿

https://segmentfault.com/a/1190000016720505

https://ithelp.ithome.com.tw/articles/10185422

node.js實現快速截圖

const webshot = require('webshot');

var options = {
streamType: 'png',
windowSize: {
width: 2048,
height: 2048
},
shotSize: {
width: 'all',
height: 'all'
}
};
webshot('URL here', 'image.png', options, function(err) {
if(err){
console.log("An error ocurred ", err);
}
else{
console.log("Job done mate :)")
}
});

https://www.itread01.com/article/1472270582.html

https://stackoverflow.com/questions/57666116/node-webshot-screenshot-of-angular-js-page-does-not-wait-for-page-load

send

res.send() will send the HTTP response. Its syntax is,

res.send([body])

這個 http res 的 body 可以是一個 buffer對象、json、html、error json ... etc,下列是它的一範例

res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.status(404).send('Sorry, we cannot find that!'); // 這個用 end() 應該會更好
res.status(500).send({ error: 'something blew up' }); // 這個用 end() 應該會更好

end

res.end() will end the response process

它是用於要結束 http 的過程,而且沒有帶任何數據的情況下,快速的作一個結束

res.end();
res.status(404).end();

send, end 需要比較一下

如果是用 send 的話會確認 output 的 structure,所以在 header 會有 content-type: text/html; charset=utf-8

反之用 end 的話就不會設定 header attribute

demo