专业的编程技术博客社区

网站首页 > 博客文章 正文

nodejs项目拆解(nodejs 模块)

baijin 2024-08-22 09:18:36 博客文章 5 ℃ 0 评论

nodejs

express框架

脚手架创建项目

express app-name

koa2框架

特点:精简,定制能力强

核心概念

中间件

· 洋葱模型

· 示例: const app = new Koa()

? app.use(async (ctx, next) => { console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL await next(); // 调用下一个middleware});app.use(async (ctx, next) => { const start = new Date().getTime(); // 当前时间 await next(); // 调用下一个middleware const ms = new Date().getTime() - start; // 耗费时间 console.log(`Time: ${ms}ms`); // 打印耗费时间});app.use(async (ctx, next) => { await next(); ctx.response.type = 'text/html'; ctx.response.body = '<h1>Hello, koa2!</h1>';});

· 为什么要使用await

? 保证洋葱模型的执行顺序

ctx,next

· ctx上下文

· 调用next()前必须加上await

· 保证洋葱模型执行顺序

· 在ctx上挂载参数,在中间件中传递

async

· 强制函数返回Promise

· 若函数中使用了await,不加async会报错

await

· 求值关键字

· 阻塞线程

参数获取

路径参数

· const path= ctx.params

查询参数

· const path= ctx.request.query

header

· const path= ctx.request.header

POST body

· 入口文件:const parser = require('koa-bodyparser')app.use(parser())路由:const path= ctx.request.body

全局异常处理

try,catch捕捉不到异步的异常

想要捕捉到异步异常,需在try里添加await释放promise中的reject

脚手架生成

cnpm install -g koa-generator

koa2 -e projectName

cd projectName && npm install

convert2img

目录结构

.├── README.md├── app.js├── bin│ └── www├── config│ └── config.js├── controllers│ └── index.js├── middleware│ ├── async.js│ ├── convert.js│ └── renderTplTohtml.js├── package-lock.json├── package.json├── public│ ├── images│ │ └── html2img│ │ ├── 1589771327371106.jpeg│ ├── javascripts│ ├── static│ │ └── images│ │ ├── audio.png│ │ ├── deco_1.png│ │ ├── deco_2.png│ │ ├── equto.png│ │ ├── icon-audio.png│ │ └── to_user_share.png│ ├── stylesheets│ │ ├── commu.css│ │ ├── commu_touser.css│ │ ├── dynamic.css│ │ ├── dynamic_touser.css│ │ ├── punch_touser.css│ │ └── reset.css│ └── tpls│ ├── tpl_commu.html│ ├── tpl_commu_touser.html│ ├── tpl_dynamic.html│ ├── tpl_dynamic_touser.html│ └── tpl_punch_touser.html├── routes│ ├── index.js│ └── users.js├── service│ ├── ali-oss.js│ └── uploadFile.js├── utils│ └── util.js└── views ├── error.ejs ├── index.ejs └── template ├── tpl_commu.ejs ├── tpl_commu_touser.ejs ├── tpl_dynamic.ejs ├── tpl_dynamic_touser.ejs ├── tpl_invite_touser.ejs └── tpl_punch_touser.ejs

tree.txt

工作原理

1 启动node项目,监听给定端口

2 http请求,进入匹配的路由

3 拿到携带的数据,渲染ejs到html(renderTplToHtml中间价)

4 使用convert中间价将html渲染为图片

项目部署

上传项目到服务器指定文件夹

安装pm2

cd到项目目录 $ npm i

nginx代理转发

小技巧

process.pwd()获取当前进程的绝对路径



8

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表