這邊你需要自己製作一個流程控制
不了解的話建可以畫個圖來確認現在在哪個流程
基本上都會回到主要操控介面
所以這邊會先建立 start 流程並呼叫對應進入頁面
index.js 呼叫流程控制
const http = require("http");
const { receiveTelegram } = require("./botHook/main");
const flowController = require("./controller/flowController");
var server = http.createServer(async function (req, res) {
let url = req.url.split("?")[0];
let paramrter = req.url.split("?")[1];
if (paramrter) paramrter = getUrlParameter(paramrter);
let data = null;
let buffers = [];
for await (const chunk of req) {
buffers.push(chunk);
}
data = Buffer.concat(buffers).toString();
data = data ? JSON.parse(data) : null;
// 上方獲取資料區
// 這邊開始實作 url
if (url === "/") {
res.writeHead(200, { "Content-Type": "application/json" });
// 實作判斷請求
if (req.method === "POST") {
if (data) {
receiveTelegram(data, res);
}
res.end();
} else {
res.write("404 page");
res.end();
}
} else {
res.write("404 page");
res.end();
}
});
server.listen(3000);
flowController.start();
/**
* @description 用來確認是否有帶參數
*
* @param {string} reqUrl url ? 後面的部分
* @return {*}
*/
function getUrlParameter(reqUrl) {
var url = reqUrl; //獲取url中"?"符後的字串
var theRequest = new Object();
var strs = null;
strs = url.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
}
return theRequest;
}
新增控制流程的 controller\flowController.js
controller\flowController.js
const viewPrinter = require("../view/viewPrinter");
class FlowController {
constructor() {}
/**
* @description 確保都拿到同一個實例
*
* @static
* @return {*}
* @memberof ConsoleItem
*/
static getInstance() {
if (!this.instance) {
this.instance = new this();
}
return this.instance;
}
/**
* @description 起始畫面
*
* @memberof FlowController
*/
async start() {
await viewPrinter.welcome();
console.log("nextTick");
}
}
let flowController = FlowController.getInstance();
module.exports = flowController;
接著製作 view\viewPrinter.js 來印畫面
view\viewPrinter.js
const consoleItem = require("../interface/consoleItem");
class ViewPrinter {
constructor() {}
/**
* @description 確保都拿到同一個實例
*
* @static
* @return {*}
* @memberof ConsoleItem
*/
static getInstance() {
if (!this.instance) {
this.instance = new this();
}
return this.instance;
}
/**
* @description 歡迎你
*
* @memberof ViewPrinter
*/
async welcome() {
return new Promise((resolve) => {
let str = [
"=======================================================",
"=======================================================",
"============ ============",
"============ Welcome Node Telegram ============",
"============ ============",
"=======================================================",
"=======================================================",
]
console.log("\x1b[36m");
for( let i = 0 ; i < str.length ; i++ ) {
setTimeout(() => {
console.log(str[i]);
if(i === str.length -1) {
console.log("\x1b[0m");
resolve();
};
}, i * 100);
}
})
}
}
let viewPrinter = ViewPrinter.getInstance();
module.exports = viewPrinter;
當然一樣不能一口氣印出來
所以弄成 Promise 確保結束後再執行下一段 nextTick
這裡是非同步與同步的概念 async await 等等