Nodejs 笔记

155 阅读3分钟

Nodejs 常见全局变量

  • __filename: 返回正在执行的脚本文件绝对路径
  • __dirname: 返回正在执行脚本所在目录
  • timer 类函数: 执行顺序和事件循环的关系
  • process: 提供当前进程互动的接口
  • require: 实现模块的加载
  • module、exports: 处理模块的导出

this

  • 默认情况下 this 是空对象
  • 自调用函数下 this 等于 global
(function () {
  console.log(this === global); //true
})();

全局变量 - process

  • memoryUsage():
console.log(process.memoryUsage());
// {
//   rss: 204636160,  当前的常驻内存
//   heapTotal: 121667584, 当前的脚本申请的总内存大小
//   heapUsed: 95443272, 当前的脚本实际所使用的内存大小
//   external: 1124745, 表示底层的C/C++ 模块所占据的模块大小
//   arrayBuffers: 32954 缓冲区的小大
// }
  • cpuUsage():
{
  user: 1241718,  //用户执行所占用的大小
  system: 58273 //操作系统执行所占用的大小
}
  • 运行环境:运行目录、node环境、cpu架构、用户环境、系统平台
console.log(process.cwd())
console.log(process.version)
console.log(process.versions)
console.log(process.arch)
console.log(process.env.NODE_ENV)
console.log(process.env.PATH)
console.log(process.env.USERPROFILE)  // HOME 获取windows/mac 的管理员目录
console.log(process.platform) //获取系统平台
  • 运行状态: 启动参数、PID、运行时间
console.log(process.argv)
console.log(process.argv0)  // execArgv
console.log(process.pid)  // ppid 
setTimeout(() => {
  console.log(process.uptime()) //获取执行所使用的时间
}, 3000)

Buffer

  • alloc 创建Buffer
  • allocUnsafe 创建Buffer(不安全)
  • from 接收数据,创建Buffer
  • fill 使用数据填充Buffer
  • write 向Buffer里写入数据
  • toString 从Buffer里提取数据
  • slice 截取Buffer
  • indexOf 在Buffer里查找数据
  • copy 拷贝Buffer的数据

Buffer静态数据

concat 将多个Buffer 拼接成一个新的Buffer

let buf1 = Buffer.from('xxx')
let buf2 = Buffer.from('yyy')

let b = Buffer.concat([buf1,buf2],3)

console.log(b.toString())

isBuffer 判断当前数据是否为Buffer

let b1 = '123'
console.log(Buffer.isBuffer(b1)) //false

flag操作符

  • r 表示可读
  • w 表示可写
  • s 表示同步
    • 表示执行相反操作
  • x 表示排它操作
  • a 表示追加操作

Fs模块

readFile 从指定文件读取数据

const fs = require('fs')
const path = require('path')

const p = path.resolve('list.txt')
console.log(p)
fs.readFile(p,'utf-8',(err:any , data: any)=>{
  if(!err){
    console.log(data)
  }
})

writeFile 向指定文件写入数据

fs.writeFile('data.txt', '123', {
  mode: 438,
  flag: 'w+',
  encoding: 'utf-8'
}, (err) => {
  if (!err) {
    fs.readFile('data.txt', 'utf-8', (err, data) => {
      console.log(data)
    })
  }
}) 

appendFile 向指定文件中追加数据

fs.appendFile('data.txt', 'hello node.js',{},  (err) => {
  console.log('写入成功')
})

copyFile 拷贝文件到指定文件

fs.copyFile('data.txt', 'test.txt', () => {
  console.log('拷贝成功')
})

watchFile 监听文件是否变化

//interval:监听的间隔时间,单位为毫秒
fs.watchFile('data.txt', {interval: 20}, (curr, prev) => {
  if (curr.mtime !== prev.mtime) {
    console.log('文件被修改了')
    fs.unwatchFile('data.txt')
  }
})

open/close 打开/关闭文件

//fd可以表示打开的文件
fs.open('data.txt','r',(err,fd)=>{
  console.log(fd)
  fs.close(fd,err=>{
    console.log('关闭成功了');
  })
})

文件操作 md 转 html

const fs = require('fs')
const path = require('path')
const marked = require('marked')
const browserSync = require('browser-sync')

//找到 md 文件路径
let mdPath = path.join(__dirname,'./index.md')
//找到 css 文件路径
let cssPath = path.resolve('github.css')
//以 md 文件名找到 html 文件
let htmlPath = mdPath.replace((path.extname(mdPath)),'.html')

function generate(){
    fs.readFile(mdPath,'utf-8',(err,data)=>{
        let htmlStr = marked(data)
        fs.readFile(cssPath,'utf-8',(err,data)=>{
            let retHtml = temp.replace('{{content}}',htmlStr).replace('{{style}}',data)
            fs.writeFile(htmlPath,retHtml,(err)=>{
                console.log('html 生成成功了');
            })
        })
    })
}

fs.watchFile(mdPath,(curr,prev)=>{
    if(curr.mtime !== prev.mtime){
        generate()
    }
})
generate()

browserSync.init({
    browser:'',
    server:__dirname,
    watch: true,
    index: path.basename(htmlPath)
})
const temp = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .markdown-body {
                box-sizing: border-box;
                min-width: 200px;
                max-width: 1000px;
                margin: 0 auto;
                padding: 45px;
            }
            @media (max-width: 750px) {
                .markdown-body {
                    padding: 15px;
                }
            }
            {{style}}
        </style>
    </head>
    <body>
        <div class="markdown-body">
            {{content}}
        </div>
    </body>
    </html>
`

利用文件的读写功能写一个 next 函数自动 copy 所有文件

const fs = require('fs')
const path = require('path')

const aPath = path.resolve(__dirname, 'a.txt')
const bPath = path.resolve(__dirname, 'b.txt')
const buf = Buffer.alloc(10)
const BUFFER_SIZE = buf.length

let offset = 0
function next(rfd,wfd){
  fs.read(rfd, buf, 0, BUFFER_SIZE, offset, (err, readBytes)=>{
    if(!readBytes){
      fs.close(rfd,()=>{})
      fs.close(wfd,()=>{})
      console.log('拷贝完成')
      return
    }
    offset += readBytes
    fs.write(wfd, buf, 0, readBytes, (err)=>{
      next(rfd,wfd)
    })
  })
}

fs.open(aPath,'r',(err,rfd)=>{
  fs.open(bPath,'w',(err,wfd)=>{
    next(rfd,wfd)
  })
})