node.js基本使用

node中模块分为:

  • 内置模块:fs,path,os,http
  • 自定义
  • 第三方

global

process

当前node.js进程

process.nextTick()下一轮事件循环

fs

readFile

1
2
3
4
5
const fs = require('fs')
//异步
fs.readFile(path [, options], (error,data)=>{
console.log(data.toString());
})
  • options:

    • encoding 编码格式,默认null,一般传入utf-8
    • flag 读取方式,默认只读r
  • 回调:

    • error表示错误
    • data:可能是字符串也可能是Buffer

writeFile

1
2
3
4
5
6
7
8
//2. 写入fs.writeFile(path, data [, options], callback)类似于fs.readFile
// data支持<string> 、 <Buffer> 、 <TypedArray> 、<DataView></DataView>
fs.writeFile('./demo.txt','123123123123',(error)=> {
if(error){
console.log('写入失败');
}
})

  • options:
    • flag :
      • 默认,’w’,覆盖,不存在就创建
      • ‘a’ 代表追加

readdir

1
2
3
const dir = fs.readdirSync(__dirname)
console.log(dir)
//返回string[]

path

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const path = require('path')
let p = './Adir/a.txt'
// /Adir/a.txt

//0. 获取根目录绝对地址
console.log(__dirname);
//__filename 当前文件的绝对地址

//1. 获取目录
console.log(path.dirname(p));

//2. 获取文件名+后缀
console.log(path.basename(p));

//3. 获取文件后缀
console.log(path.extname(p));

//4. 将路径解析为绝对路径,可以接收任意个参数
console.log(path.resolve(__dirname,p));

//5. join 连接路径
console.log(path.join(__dirname, './file.txt'))

url

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const url = require('url')

const str = 'https://www.google.com:8080/a/b?x=1&y=2&y=3&y=4#qq=2522'

// parse('url', bool ) //布尔表示把query参数转换成对象

console.log(url.parse(str,true));
/*
Url {
protocol: 'https:', 协议
slashes: true,
auth: null,
host: 'www.google.com:8080', //主机= 域名+端口
port: '8080', //端口
hostname: 'www.google.com', //域名
hash: #qq=2522, //hash值
search: '?x=1&y=2&y=3&y=4',
query: 'x=1&y=2&y=3&y=4', //query参数
pathname: '/a/b', //路径
path: '/a/b?x=1&y=2&y=3&y=4',
href: 'https://www.google.com:8080/a/b?x=1&y=2&y=3&y=4#qq=2522'//原地址
}
*/


#Buffer

用来存储二进制数据,(以0~F表示)

每个元素1B

一旦确定Buffer大小,后续不能改变

默认都是utf-8

常用方法:

  1. Buffer.from(str [,encoding]): 把一个字符转换为Buffer
  2. Buffer.alloc(size): 创建指定大小的Buffer
  3. Buffer.allocUnsafe(size): 创建时不会清理地址原始数据
  4. buf.toString(): 把Buffer转换为字符串