node学习笔记【2022】

对node的一次学习总结吧,佛系书写,个人觉得里面的知识点还是常用的,后续重新学习或有更深的认识,会在本文翻新甚至重构内容,不懂的还是直接翻阅官网文档进行查阅吧,这么多API和知识点不可能都记得下来。

什么是nodejs

基于v8引擎的运行时环境,开发人员必备环境,就不展开说了。知道最基本的install 指定版本、use切换、list查看就行

Node的几种常见的导入导出方式

常见的三种导出方式,一:在方法或者变量前加export,二:将定义好的变量通过变量名导出,三:导出的时候给变量起别名(比较少用)。

export const myName = '小明'

const name = ”mm“
const sayHello= () => {}
export { name , sayHello }

export {
	name as Name,
    sayHello as SayHello
}

常见的四种导入方式:一:import { } from ‘./路径.js’,二:导出变量后起别名,三:通过* as foo,四:export和import的结合使用(了解就好,基本不会用到)

import { name } from './路径/文件.js'   //.js 不能省略

// 导出的时候起过别名fName
import { fName as wNamme } from './路径.js'

import * as foo from './路径.js'

export { name, age} form './xxx.js'

这个会最经典的就行,一个import 一个export 走天下。

Node中的常用内置模块

1.path模块(拼接路径),它有几种方法,如拼接路径,获取路径,获取文件名,获取文件后缀等。具体看下面例子

const path = require('path')
const basePath = '/User'
const fileName = '/abc.txt'

// 拼接路径
const filePath = path.reslove(basePath, fileName)
const filepath = '/User/yogln/abc.txt'
// 获取路径
path.dirname(filepath)
// 获取文件名
path.basename(filepath)
// 获取文件的后缀名
path.extname(filepath)

2.fs模块(文件系统),获取文件信息操作方式这块比较常用,有js基础的,基本看一遍都晓得大概,同步异步Promise,很经典了。只不过在Node中用的是fs实现。这还有一块的文件操作内容,算比较常用吧,W写入,R读,A在打开文件且末尾追加,都采用了英文首字母方式定义,比较好记。

const fs = require('fs')
const filepath = './abc.txt'

// 获取文件信息操作方式
// 1. 方式一:同步操作,后续需要执行的代码会被阻塞
const info = fs.ststSync(filepath)
console.log(info)            

// 2. 方式二:异步方式
fs.stat(filepath, (err, info) => {
    if(err) {
        console.log(err)
        return
    }
    console.log(info)
})

// 3. 方式三: promise
fs.promises.stat(filepath).then(info => {
    console.log(info)
}).catch(err => {
    console.log(err)
})

// 在文件末尾追加
fs.writeFile('./abc.txt', content, {flag: "a"}, err => {
  console.log(err)
})

node操作mysql

这里说下预处理语句执行mysql吧,他相对于传统方式更加安全,能有效防止sql注入,性能方面也略胜一筹。

const mysql = require('mysql2')

// 1. 创建一个数据库连接
const connection = mysql.createConnection({
  host: 'localhost',
  port: 3306,
  database: 'school',
  user: 'root',
  password: 'root'
})
// 2. 执行预处理语句
const statement = `select * from students where age > ?`

connection.execute(statement, [18], (err, res) => {
  console.log(res)
  connection.destroy()
})

创建自己的脚手架工具

大概五步吧。
一:在创建好相应的项目里,有index.js入口文件,执行npm init -y 初始化一个package.json文件,在里面配置:

"bin": {
    "xyl": "index.js"
  },
// xyl为命令
// index.js 事要执行的文件

然后执行npm link 命令,在终端种输入xyl,执行index文件。

二:项目中先下载commander,npm install commander

const program = require('commander')
// 查看版本号,通过require请求道package.json对象拿到version
program.version(require('./package.json').version)

// 通过process进程的参数解析我们输入的命令
program.parse(process.args)

然后执行xyl --version命令即显示版本号,xyl – help命令默认

三:额外的操作:

// 增加自己的options
program.option('-x --xyl','a xyl cli')
program.option('-d --dest <dest>','a destination floder,例如:-d/src/components')
// 监听
program.on('--help', ()=> {
  console.log("Other: ")
  console.log("   other options~")
})

四:使用create 命令创建项目,首先得新建create.js

const program = require('commander')

const  creatCommand =() => {

  program
    .command('create <project> [others...]') //命令
    .description('clone repository into a floder') //描述
    .action((project, others) => { //动作
      console.log(project, others)
    })

}
module.exports = creatCommand

在index.js中调用const program = require('commander')// 创建其他指令creatCommand()

五:开发自己的脚手架工具并在NPM上发布,这块有点复杂,看了老半天不是很明白,就不误人子弟了。

http开发web服务器

const http = require('http')

// 创建一个web服务器
const server = http.createServer((req,res) => {
  res.end('hello server')
})

// 启动服务器  (端口号0-65535, 主机, )
server.listen(8000, '0.0.0.0', () =>{
  console.log('服务器启动成功')
})

这里为了每次修改代码后,服务器能够自动重启可以安装工具nodemon,通过nodemon启动服务器nodemon index.js
上面例子中,还可以通过以下方式创建服务器,他俩是一样的。

 const server = new http.Server((req,res) => {
  res.end('hello server')
})

这里就可以监听主机和端口号了,Server通过listen方法来开启服务器并且在某一个主机和端口上监听网络请求,也就是当我们通过 ip:port的方式发送到我们监听的Web服务器上时,我们就可以对其进行相关的处理。

初体验expresss框架

脚手架安装、创建项目,安装依赖,运行一套操作行云流水。
最常见的操作:

const express = require('express')
// express其实是一个函数: createApplication
// 返回appconst app = express()
// 监听默认路径
app.get('/', (req, res, next) => {  res.end('hello express')})
app.post('/login', (req, res, next) => {  res.end('欢迎登录')})
// 开启监听
app.listen(8000, () => {  console.log('express启动成功')}) 

当然它还能作为中间件使用:也是常见的中间件简略版。

const express = require('express')const app = express()
// 编写普通的中间件
// use方式注册一个中间件
app.use((req, res, next) => {  console.log('注册一个普通中间件01')  
res.end('结束请求')  next()})
app.use((req, res, next) => {  console.log('注册一个普通中间件02')  
res.end('结束请求')  next()})
//如果这里写入了会报错,原因十因为上面的中间件已经结束了响应   

app.listen(8000, (req, res, next) => {  console.log('普通的中间件')}

从这里可以延伸出很多中间件实例,比如路径匹配,路径拼接的中间件,注册用的,body参数解析(body-parse)中间件,formdata解析,request参数解析等,还是比较重要的吧。

初体验koa框架

还是老样子,脚手架安装、创建项目,安装依赖,运行一套操作行云流水。

const Koa = require('koa')
const app = new Koa()
app.use((ctx, next) => {  
	console.log('中间件被执行')  
	// 返回结果  
	ctx.response.body = "我是返回的结果"
})
app.listen(8000, () => {  console.log('koa服务器启动成功') })

值得注意的是:

  • koa中间件只能通过use注册,没有提供app.use(‘/login’, ())这种方式
  • 没有app.get,app.post等方法
  • 也没有提供连续注册中间件的方式

另外,koa中路由的使用大致为(需要安装 koa-router):

const Router = require('koa-router')
const router = new Router({prefix: '/users'})
router.get('/', (ctx, next) => { 
 	ctx.response.body = 'get request'
})
router.put('/', (ctx, next) => { 
	ctx.response.body = 'put request'
})
module.exports = router

koa和express的区别

  • express趋向完整和强大的,其中帮助我们内置了非常多好用的功能。
  • koa是简洁和自由的,它只包含最核心的功能,并不会对我们使用其他中间件进行任何的限制。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值