顯示具有 Nodejs 標籤的文章。 顯示所有文章
顯示具有 Nodejs 標籤的文章。 顯示所有文章

WebSocket+Express讓前後端一家親

因為不想廢話,這裡就不解釋什麼是WebSocket了XD,進入正題

這裡直接使用Github上的websockets/ws項目,它直接使用了express做為項目,所以我們也一起跟著用吧XD

連結在這 https://github.com/websockets/ws

這裡我只寫我做的結果,所有的內容會放到github上,也會給上連接

Server的code

const wss = new WebSocket.Server({
port: WSS_PORT
});

wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('client send: %s', message)
});
setInterval(() => {
var uuid = uuidv4()
ws.send(uuid);
console.log('server send: %s', uuid)
}, 1000)
});

假裝Server有一直在傳輸信息所以使用setInterval 代替 


Client的code


<body onload="onload()">

<h1>Hello WebSockets</h1>

</body>

<style>
body {
background-color: lightblue;
overflow: auto;
}
</style>

<script>
function onload() {

let ws = new WebSocket('ws://localhost:8080')
ws.onopen = () => {
console.log('open connection')
}
ws.onclose = () => {
console.log('close connection')
}
ws.onmessage = event => {
console.log('client收到server信息')
console.log(event.data)
var msg = document.createElement('div')
msg.innerHTML = event.data;
document.querySelector('body').append(msg);
msg.focus();

}

}
</script>

執行server.js查看效果

Server console

Client page

Client console

完整的項目在這

https://github.com/cn27529/express-ws

收工


參考自

https://letswrite.tw/websocket/

https://medium.com/enjoy-life-enjoy-coding/javaScript-websocket-讓前後端沒有距離


vscode-Bracket Pair Colorizer-有了彩色括號不再眼花惹

code多了會對很多的括號們也一定會眼花, 今天在這不是要賣你藥吃, 吃了會一目十行百行, 因為你不是神童, 今天要來說一款好用Bracket Pair Colorizer外掛套件, 不廢言, 來吧.



雖然星星數不多, 反正好用就好了XD


如果你的NB或PC效能比較慢, 你會發現這個效果不會主立馬出現, 所以看你嘍XD



收工!



EJS常用標簽

常用的EJS標簽XD

<% %>流程控制標簽
//例
<% var user.name = 'bruce - huang' %>
<% if(user.name !== null) { %>
<div>hi <%= user.name %></div>
<% } else { %>
<div>no user name</div>
<% } %>

<%= %>输出標簽(原文输出HTML標簽)
//例
<% var user.name = 'bruce - huang' %>
<%= user.name %>

<%- %>输出標簽(HTML会被浏览器解析)
//例
<%- data.htmlContent %>


<%# %>注释標簽
//例
<%# 我是注解,我不會被秀在源始碼上 %>

-%>去掉沒用的空格
//例
<% var user.name = 'bruce - huang 看己去試吧, 我是不知道他怎知道什麼叫沒用的空格XD' %>
<%= user.name -%>

ejs中的邏輯代碼全部用JavaScript

好了, 收工!!

pm2, App name

具官方文件是長這樣

pm2 start app.js           # Start app.js

pm2 start app.js -- -a 23  # Pass arguments '-a 23' argument to app.js script

pm2 start app.js --name serverone # Start a process and name it as serverone
                                    # you can now stop the process by doing
                                    # pm2 stop serverone
別名其實是很方便的東西...

按官方指示, 在實際上使用時, 你會發現....


在參數搭配別名時會變成這樣..

原來是....別名在前, 參數在後

完工

pm2, node的程序(進程)管理工具, 使用與教學

今天的東東叫pm2, pm2是node的一個可監控程序的工具, 不多廢, 進主題

進行全域安裝
workspace npm install pm2 -g                                                                                                                           
/home/cabox/.nvm/versions/node/v5.2.0/bin/pm2 -> /home/cabox/.nvm/versions/node/v5.2.0/lib/node_modules/pm2/bin/pm2                                       
/home/cabox/.nvm/versions/node/v5.2.0/bin/pm2-dev -> /home/cabox/.nvm/versions/node/v5.2.0/lib/node_modules/pm2/bin/pm2-dev                               
/home/cabox/.nvm/versions/node/v5.2.0/bin/pm2-docker -> /home/cabox/.nvm/versions/node/v5.2.0/lib/node_modules/pm2/bin/pm2-docker                         
/home/cabox/.nvm/versions/node/v5.2.0/bin/pm2-daemon -> /home/cabox/.nvm/versions/node/v5.2.0/lib/node_modules/pm2/bin/pm2-daemon                         
/home/cabox/.nvm/versions/node/v5.2.0/bin/pm2-runtime -> /home/cabox/.nvm/versions/node/v5.2.0/lib/node_modules/pm2/bin/pm2-runtime                       
/home/cabox/.nvm/versions/node/v5.2.0/lib                                                                                                                 
`-- pm2@2.5.0                                                                                                                                             
                                                                                                                                                          
npm WARN optional Skipping failed optional dependency /pm2/chokidar/fsevents:                                                                             
npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.1.2                                                                 
➜  workspace          
YA裝好了, 目前安裝的是2.5.0版本

如何使用它
進入到你的node app資夾, 一般情況下都是執行npm start啟動你的node app
start的內容多半是指定在package.json裡, 可以去看就道了, 如果你的啟動是index.js
那就是...
bk git:(master) pm2 start index.js                                                                                                                     
[PM2] Starting /home/cabox/workspace/bk/index.js in fork_mode (1 instance)                                                                                
[PM2] Done.                                                                                                                                               
┌──────────┬────┬──────┬──────┬────────┬─────────┬────────┬─────┬───────────┬──────────┐                                                                  
│ App name │ id │ mode │ pid  │ status │ restart │ uptime │ cpu │ mem       │ watching │                                                                  
├──────────┼────┼──────┼──────┼────────┼─────────┼────────┼─────┼───────────┼──────────┤                                                                  
│ index    │ 0  │ fork │ 9660 │ online │ 0       │ 0s     │ 0%  │ 13.3 MB   │ disabled │                                                                  
└──────────┴────┴──────┴──────┴────────┴─────────┴────────┴─────┴───────────┴──────────┘                                                                  
 Use `pm2 show ` to get more details about an app  
瞧, 有了! 這樣就開始被監控了, 然後你的app 也啟動了

也是可以將App name命名, 如
bk git:(master) pm2 start index.js --name myapp                                                                                                        
[PM2] Spawning PM2 daemon with pm2_home=/home/cabox/.pm2                                                                                                  
[PM2] PM2 Successfully daemonized                                                                                                                         
[PM2] Starting /home/cabox/workspace/bk/index.js in fork_mode (1 instance)                                                                                
[PM2] Done.                                                                                                                                               
┌──────────┬────┬──────┬───────┬────────┬─────────┬────────┬─────┬───────────┬──────────┐                                                                 
│ App name │ id │ mode │ pid   │ status │ restart │ uptime │ cpu │ mem       │ watching │                                                                 
├──────────┼────┼──────┼───────┼────────┼─────────┼────────┼─────┼───────────┼──────────┤                                                                 
│ myapp    │ 0  │ fork │ 10014 │ online │ 0       │ 0s     │ 0%  │ 13.4 MB   │ disabled │                                                                 
└──────────┴────┴──────┴───────┴────────┴─────────┴────────┴─────┴───────────┴──────────┘                                                                 
 Use `pm2 show ` to get more details about an app 
瞧, 有了! 己變成myapp, 然後你的app 也啟動了, 去看看吧
(app啟動無圖) XD

接下來看看監控的dashboard
bk git:(master) pm2 monit       
會出現下列
Process list ─────────────────────────────┐┌─ Global Logs ───────────────────────────────────────────────────────────────────────────────────────────┐ 
│[ 0] myapp     Mem:  44 MB    CPU:  0 %  on ││ myapp > Executing (default): SELECT `id`, `title`, `body`, `noteday`, `createdAt`, `updatedAt`,         │ 
│                                            ││ `ProfileId` FROM `Notes` AS `Note`;                                                                     │ 
│                                            ││ myapp > Executing (default): SELECT `id`, `email`, `password`, `createdAt`, `updatedAt` FROM            │ 
│                                            ││ `Accounts` AS `Account`;                                                                                │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
│                                            ││                                                                                                         │ 
└────────────────────────────────────────────┘└─────────────────────────────────────────────────────────────────────────────────────────────────────────┘ 
┌─ Custom metrics (http://bit.ly/code-metric─┐┌─ Metadata ──────────────────────────────────────────────────────────────────────────────────────────────┐ 
│ Loop delay                         0.47ms  ││ App Name              myapp                                                                             │ 
│                                            ││ Restarts              0                                                                                 │ 
│                                            ││ Uptime                14m                                                                               │ 
│                                            ││ Script path           /home/cabox/workspace/bk/index.js                                                 │ 
│                                            ││ Script args           N/A                                                                               │ 
│                                            ││ Interpreter           node                                                                              │ 
│                                            ││ Interpreter args      N/A                                                                               │ 
│                                            ││ Exec mode             fork                                                                              │ 
│                                            ││ Node.js version       5.2.0                                                                             │ 
│                                            ││ watch & reload        ?                                                                                 │ 
└────────────────────────────────────────────┘└─────────────────────────────────────────────────────────────────────────────────────────────────────────┘ 
瞧, 是不是, 監控畫面開啟了

如何停止它
workspace pm2 stop myapp                                                                                                                               
[PM2] Applying action stopProcessId on app [myapp](ids: 0)                                                                                                
[PM2] [myapp](0) ✓                                                                                                                                        
┌──────────┬────┬──────┬───────┬─────────┬─────────┬────────┬─────┬───────────┬──────────┐                                                                
│ App name │ id │ mode │ pid   │ status  │ restart │ uptime │ cpu │ mem       │ watching │                                                                
├──────────┼────┼──────┼───────┼─────────┼─────────┼────────┼─────┼───────────┼──────────┤                                                                
│ myapp    │ 0  │ fork │ 0     │ stopped │ 0       │ 0      │ 0%  │ 0 B       │ disabled │                                                                
│ myapp2   │ 1  │ fork │ 10826 │ online  │ 0       │ 2m     │ 0%  │ 24.2 MB   │ disabled │                                                                
└──────────┴────┴──────┴───────┴─────────┴─────────┴────────┴─────┴───────────┴──────────┘                                                                
 Use `pm2 show ` to get more details about an app                                 
瞧, myapp己停止了

如何刪除它
workspace pm2 delete myapp                                                                                                                             
[PM2] Applying action deleteProcessId on app [myapp](ids: 0)                                                                                              
[PM2] [myapp](0) ✓                                                                                                                                        
┌──────────┬────┬──────┬───────┬────────┬─────────┬────────┬─────┬───────────┬──────────┐                                                                 
│ App name │ id │ mode │ pid   │ status │ restart │ uptime │ cpu │ mem       │ watching │                                                                 
├──────────┼────┼──────┼───────┼────────┼─────────┼────────┼─────┼───────────┼──────────┤                                                                 
│ myapp2   │ 1  │ fork │ 10826 │ online │ 0       │ 11m    │ 0%  │ 22.7 MB   │ disabled │                                                                 
└──────────┴────┴──────┴───────┴────────┴─────────┴────────┴─────┴───────────┴──────────┘                                                                 
 Use `pm2 show ` to get more details about an app       
瞧, myapp己被刪了

不再用它時

好了, 關閉pm2的監控吧
bk git:(master) pm2 kill                                                                                                                               
[PM2] Stopping PM2...                                                                                                                                     
[PM2] Applying action deleteProcessId on app [all](ids: 0)                                                                                                
[PM2] [myapp](0) ✓                                                                                                                                        
[PM2] All processes have been stopped and deleted                                                                                                         
[PM2] PM2 stopped                                                 

workspace pm2 list                                                                                                                                     
[PM2] Spawning PM2 daemon with pm2_home=/home/cabox/.pm2                                                                                                  
[PM2] PM2 Successfully daemonized                                                                                                                         
┌──────────┬────┬──────┬─────┬────────┬─────────┬────────┬─────┬─────┬──────────┐                                                                         
│ App name │ id │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ watching │                                                                         
└──────────┴────┴──────┴─────┴────────┴─────────┴────────┴─────┴─────┴──────────┘                                                                         
 Use `pm2 show ` to get more details about an app              
瞧, 己經沒有app被監控了

收工, 今天就介紹到這兒吧, 下次再做進階的應用, 881~