skip to content
天真笔录

node基础复习

/ 2 min read

path 模块

  1. resolve() 返回绝对路径
  2. parse() 解析路径
  3. format() 序列化路径
  4. normalize() 规范化路径
  5. basename() 狭取路径中基础名称
  6. dirname() 获取路径中目录名称
  7. extname() 获取路径中扩展名称
  8. isAbsolute() 获取路径是否为绝对路径
  9. join() 拼接多个路径片段

ESM中使用filename,dirname,require

import { fileURLToPath } from "url";
import { dirname } from "path";
import { createRequire } from "module";

const __filename = fileURLToPath(import.meta.url);

console.log(`__filename`, __filename);
console.log(`dirname`, dirname(__filename));

const require = createRequire(import.meta.url);
console.log(require("./package.json").name);

process

  • process.memoryUsage()
  • process.cpuUsage()
  • process.cwd()
  • process.version
  • process.versions
  • process.arch // 64/32
  • process.env.NODE_ENV
  • process.env.PATH // 系统变量
  • process.env.USERPROFILE // windows 系统目录
  • process.env.HOME // mac linux 系统目录
  • process.platform
  • process.argv // 命令参数
  • process.pid
  • process.uptime() // 执行脚本耗时

01

异步IO

readFile

Buffer

缓冲区 缓冲合并

http

http.createServe html

  1. url, methodea
  2. 404 500
  3. head accept.indexOf(‘image/*‘)
  4. 1. readFile性能问题 2000k 2. fs.createReadStream + fs.createWriteStream + pipe

cli

依赖安装

pnpm add commander download-git-repo ora handlebars figlet clear chalk open

#指定脚本解释器为node
#!/usr/bin/env node
console.log('cli......')

package.json

"bin": {
    "kkb": "./bin/kkb.js"
  },

npm link npm link —global // 等同全局安装

clone脚手架

lib/download.js

koa

解决了什么问题?

  1. 提供了优雅的API
  2. 洋葱模型 AOP实现