Node.js基础知识——经常使用API

记录Node.js经常使用的API。css

推荐阅读路线

1 Buffer类

原生JavaScript中没有处理二进制数据流的机制,而服务端有处理二进制数据流的需求,对此,nodeJS引入了Buffer类来处理二进制数据。html

1.1 实例化方法

1.1.1 Buffer.alloc(size[, fill[, encoding]])

// 建立一个长度为3,值为0的Buffer
const buf1 = Buffer.alloc(3)
console.log(buf1)
// 输出:<Buffer 00 00 00>

// 建立一个长度为3,值为16的Buffer
const buf2 = Buffer.alloc(3, 16)
console.log(buf2)
// 输出:<Buffer 10 10 10>

//encoding是编码方式,默认为utf8
复制代码

1.1.2 Buffer.from(array)

// 接收一个整数数组,返回一个buffer对象
const buf = Buffer.from([1, 2, 3])
console.log(buf)
// 输出<Buffer 00 02 03>
复制代码

1.1.3 Buffer.from(string[, encoding])

// 接收一个字符串,返回一个buffer对象,encoding是编码方式,默认为utf8
const buf = Buffer.from('Hello World!')
console.log(buf.toString())
// 输出Hello World!
复制代码

1.2 静态方法

1.2.1 Buffer.isEncoding(encoding)

// 判断是否支持某种编码方式
console.log(Buffer.isEncoding('utf8')) //输出true
console.log(Buffer.isEncoding('ascii')) //输出true
console.log(Buffer.isEncoding('base64')) //输出true
复制代码

1.2.2 Buffer.isBuffer(obj)

// 判断是否为Buffer对象
console.log(Buffer.isBuffer(Buffer.alloc(3)))   // 输出true
console.log(Buffer.isBuffer('000')) // 输出false
复制代码

1.2.3 Buffer.byteLength(string[, encoding])

// 返回指定编码方式的字符串长度
const str = '\u00bd + \u00bc = \u00be' // Unicode编码的字符串
console.log(str.length) // Unicode编码的字符串长度为9
console.log(Buffer.byteLength(str,'utf8')) // utf8编码的字符串长度为12
复制代码

1.2.4 Buffer.concat(list[, totalLength])

// 合并传入的buffer数组,totalLength表示最终返回的buffer的长度
const buf1 = Buffer.alloc(1, 1)
const buf2 = Buffer.alloc(1, 2)
const buf3 = Buffer.alloc(1, 3)
const buf4 = Buffer.concat([buf1, buf2, buf3])
console.log(buf4)
// 输出<Buffer 01 02 03>
const buf5 = Buffer.concat([buf1, buf2, buf3], 2)
console.log(buf5)
// 输出<Buffer 01 02>
const buf6 = Buffer.concat([buf1, buf2, buf3], 4)
console.log(buf6)
// 输出<Buffer 01 02 03 00>
复制代码

1.3 实例方法

1.3.1 buf.write(string[, offset[, length]][, encoding])

// 向buffer写入内容,offset为开始写入的位置,length为写入的长度,encoding为写入内容的编码方式
const buf = Buffer.alloc(10);
buf.write('hello',1 , 4) //在1的位置开始写入前4位的'hello'
console.log(buf)
// 输出<Buffer 00 68 65 6c 6c 00 00 00 00 00>
console.log(buf.toString())
// 输出hell
复制代码

1.3.2 buf.slice([start[, end]])

// 截取buffer的一部分,start是开始位置,不传则复制整个buf,end为结束位置,不传则截取到最后一位
const buf1 = Buffer.from('Hello World!')
const buf2 = buf1.slice(1, 5)
const buf3 = buf1.slice(1)
const buf4 = buf1.slice()
console.log(buf2.toString())
console.log(buf3.toString())
console.log(buf4.toString())
// 输出ello  
//     ello World!
//     Hello World!
复制代码

1.3.3 buf.toString([encoding[, start[, end]]])

// 将二进制数据流转换为字符串,encoding是编码方式,start与end效果同slice相似
const buf = Buffer.from('Hello World!')
console.log(buf.toString('utf8',1,5))
console.log(buf.toString('utf8',1))
console.log(buf.toString('utf8'))
// 输出ello  
//     ello World!
//     Hello World!
复制代码

2 path - 操做路径对象

path不在全局做用域中,须要先引入再使用前端

const path = require('path')
复制代码

2.1 方法

2.1.1 path.basename(path[, ext])

// 得到文件名及文件后缀,ext是文件后缀,若ext与实际文件后缀匹配则不输出文件后缀,不然忽略ext
const basename1 = path.basename('/a/b/c/d/index.html')
const basename2 = path.basename('/a/b/c/d/index.html','.html')
const basename3 = path.basename('/a/b/c/d/index.html','.css') // 第二个参数会被忽略
console.log(basename1, basename2, basename3)
// 输出index.html  index  index.html
复制代码
2.1.2 path.dirname(path)
// 得到不带文件名的文件路径
const dirname = path.dirname('/a/b/c/d/index.html')
console.log(dirname)
// 输出 /a/b/c/d
复制代码

2.1.3 path.extname(path)

// 得到文件后缀名
const extname = path.extname('/a/b/c/d/index.html')
console.log(extname)
// 输出 .html
复制代码

2.1.4 path.parse(path)

// 将路径字符串转换为路径对象
const pathObj = path.parse('E:\\a\\b\\c\\d\\index.html')
console.log(pathObj)
/* 输出
 * { 
 *  root: 'E:\\', // 文件根目录
 *  dir: 'E:\\a\\b\\c\\d', // 不带文件名的文件路径
 *  base: 'index.html', // 文件名
 *  ext: '.html', // 文件后缀
 *  name: 'index' // 不带后缀的文件名
 * }
 */
复制代码

2.1.5 path.format(pathObj)

// 将路径对象转换为路径字符串
const pathObj = {
  root: 'E:\\',
  dir: 'E:\\a\\b\\c\\d',
  base: 'index.html',
  ext: '.html',
  name: 'index'
}
console.log(path.format(pathObj))
// 输出 E:\a\b\c\d\index.html
// 注意:路径对象的每一个属性不是必须的,提供了dir属性时会忽略root属性,提供了base属性时会忽略ext与name属性
复制代码

2.1.6 path.isAbsolute(path)

// 判断路径是不是绝对路径
console.log(path.isAbsolute('E:/a/b/c/d\index.html'))
console.log(path.isAbsolute('./a/b/c/d\index.html'))
// 输出 true false
复制代码

2.1.7 path.join([...paths])

// 接收一组路径,并拼接为一个路径,../表示返回上一级目录,./表示同级目录
console.log(path.join('/a/b/c/d','../','./','index.html'))
// 输出 \a\b\c\index.html
复制代码

2.1.8 path.relative(from, to)

// 接收两个路径,返回第一个路径到第二个路径的相对路径
const to = 'C:\\orandea\\test\\aaa'
const from = 'C:\\orandea\\impl\\bbb'
console.log(path.relative(to, from))
// 输出 ..\..\impl\bbb
复制代码

2.2 属性

2.2.1 path.delimiter

// 环境变量分隔符
console.log(path.delimiter)
// windows下输出; Linux下是:
复制代码

2.2.2 path.sep

// 路径分隔符
console.log(path.sep)
// windows下输出\ Linux下是/
复制代码

3 fs - 操做文件对象

fs不在全局做用域中,须要先引入再使用node

const path = require('fs')
复制代码

3.1 fs.readFile(path[, options], callback)

首先在同级目录中建立文件text.text,内容为Hello World!,稍后打印出来git

// 异步读取文件内容
// 第一个参数为目标文件路径
// 第二个参数为可选参数,指定读取出来的字符编码(encoding)及读写权限(flag),不指定字符编码时,默认输出二进制字节流
// 第三个参数为读取成功后的回调函数
// 回调函数有两个参数,第一个参数是错误参数,为null表示未发生错误,第二个参数为读取出来的内容字符串
fs.readFile(path.join('./text.text'),{encoding: 'utf8'}, (err,fileContent) => {
  if(err !== null) {
    // 输出错误信息
    console.log(err.stack)
  } else {
    // 输出utf8编码的Hello World!
    console.log(fileContent)
  }
})
复制代码

3.2 fs.readFileSync(path[, options])

// 同步读取文件内容,同步执行时没有回调函数,须要自定处理错误,函数返回文件内容
try {
  const fileContent = fs.readFileSync(path.join('./text.tet'),{encoding: 'utf8'})
  // 输出utf8编码的Hello World!
  console.log(fileContent)
} catch(err) {
  console.log('写入文件发送错误,请检查文件路径')
}
复制代码

3.3 fs.writeFile(path, data[, options], callback)

// 异步写入文件内容
// path与options参数同上,第二个参数data为写入的内容,回调函数只有一个错误对象参数err
fs.writeFile(path.join('./text.text'), 'Hello World!!!', {encoding: 'utf8'}, err => {
  if(err !== null) {
    console.error(err.stack)
  }
})
// 再次查看text.text文件会发现内容改成了Hello World!!
复制代码

3.4 fs.writeFileSync(path, data[, options])

// 同步写入文件内容
try {
  fs.writeFileSync('./text.text','Hello World!!!',{encoding: 'utf8'})
} catch (err) {
  console.log('写入文件发送错误,请检查文件路径')
}
// 再次查看text.text文件会发现内容改成了Hello World!!!
复制代码

3.5 文件对象

3.5.1 获取文件对象

3.5.1.1 fs.stat(path, callback)
// 异步获取文件对象
// 回调函数的第二个参数即为文件对象
fs.stat('./text.text',(err, stat) => {
  if(err) {
    console.log(err.stack)
  } else {
    console.log(stat)
  }
})
复制代码
3.5.1.2 fs.statSync(path)
// 同步获取文件对象
try {
  const stat = fs.statSync('./text.text')
  console.log(stat)
} catch (err) {
  console.log('写入文件发送错误,请检查文件路径')
}
复制代码

3.5.2 文件对象方法

3.5.2.1 stats.isDirectory()
// 判断当前文件对象是不是文件目录
复制代码
3.5.2.2 stats.isFile()
// 判读单当前文件对象是不是常规文件
复制代码

3.5.3 文件对象属性

3.5.3.1 birthtime
// 文件建立时间
复制代码
3.5.3.2 atime
// 文件访问时间
复制代码
3.5.3.3 mtime
// 文件修改时间(指文件数据被修改)
复制代码
3.5.3.4ctime
// 文件修改时间(指文件访问权限被修改)
复制代码

3.6 fs.mkdir(path[, options], callback)

// 异步建立一个文件目录,第二个参数能够经过recursive设置是否同时建立子文件夹

// 不存在a文件夹的时候会报错
fs.mkdir('./a/b',err => {
  if(err) {
    console.log(err.stack)
  }
})
// 设置第二个参数,在不存在a目录的时候自动建立a目录,而后在a目录中建立b目录
fs.mkdir('./a/b/c', {recursive: true}, err => {
  if(err) {
    console.log(err.stack)
  }
})
复制代码

3.7 fs.mkdirSync(path[, options])

// 同步建立文件夹
try {
  fs.mkdirSync('./a/b', {recursive: true})
} catch (err) {
  console.log('建立文件夹错误')
}
复制代码

3.8 fs.readdir(path[, options], callback)

// 异步读取一个目录下的全部文件及文件夹
// __dirname是当前文件所在目录的路径
fs.readdir(__dirname,(err, files) => {
	if(err) {
    	console.log(err.stack)
	} else {
	    // 输出指定目录下的全部文件名及文件夹名组成的数组
	    console.log(files)
	}
})
复制代码

3.9 fs.readdirSync(path[, options])

// 同步读取一个目录下的全部文件及文件夹
try {
  const files = fs.readdirSync(__dirname)
  console.log(files)
} catch (err) {
  console.log('读取文件夹错误')
}
复制代码

3.10 fs.rmdir(path, callback)

// 异步删除空文件夹
fs.rmdir('./a', err => {
  if(err) {
    console.log(err.stack)
  }
})
// 注意:只能删除空的文件夹,想要删除非空文件夹可使用递归
复制代码

3.11 fs.rmdirSync(path)

// 同步删除空文件夹
try {
  fs.rmdirSync('./a')
} catch (err) {
  console.log('删除文件夹失败')
}
复制代码

4 全局属性及方法

4.1 __dirname

// 当前文件所在的目录的路径
console.log(__dirname)
// 输出 E:\demo\node
复制代码

4.2 __filename

// 当前文件的路径
console.log(__filename)
// 输出 E:\demo\node\node\global.js
复制代码

5 http - 操做网络请求

http模块须要先引入再使用github

const http = require('http')
复制代码

5.1 建立一个服务器并监听一个端口

// 建立一个http server对象,用于监听某个端口,制做一个服务器
const server = http.createServer((req, res) => {
    // 返回响应并设置返回的内容
    res.end('Hello World!')
})
// 监听3000端口
server.listen(3000)
// 此时在浏览器中访问localhost:3000便可看到返回的内容
复制代码

5.2 http.createServer参数中的req对象

req(request)对象是http的请求对象,是http.IncomingMessage的实例,咱们能够在req对象中得到请求头部,请求体中的参数等信息。express

5.2 http.createServer参数中的res对象

res(response)对象是http的响应对象,是http.ServerResoponse的实例,咱们能够经过res的方法设置响应信息。windows

5.2.1 res.write()

// 写入响应内容
const server = http.createServer((req, res) => {
    // 设置返回的内容
    res.write('Hello World!')
    // 返回响应
    res.end()
})
复制代码

5.2.2 res.setHeader()

// 设置响应头部
const server = http.createServer((req, res) => {
    // 设置内容类型为text/plain,编码方式为utf-8
    res.setHeader('Content-Type', 'text/plain; charset=utf8')
    // 返回响应并设置返回的内容
    res.end('Hello World!')
})
复制代码

5.2.3 res.writeHead()

// 设置响应状态码
const server = http.createServer((req, res) => {
    // 设置响应状态码为404
    res.writeHead(404)
    // 返回响应并设置返回的内容
    res.end('Hello World!')
})
复制代码

6 url - 解析url模块,多用于得到get请求的参数

url须要先引入再使用数组

const url = require('url')
复制代码
// 请求url能够经过req对象得到
const server = http.createServer((req, res) => {
    // 请求地址url
    console.log(req.url)
    res.end()
})
复制代码

6.1 url.parse(urlString[, parseQueryString])

// 获取前端发送的get请求的参数
// 第一个参数为url,第二个参数为是否将参数由字符串转换为对象
const urlString = 'localhost:3000?username=admin&password=123'
// 重点看query参数,query参数是前端发送的参数
console.log(url.parse(urlString).query)
// 输出 username=admin&password=123

console.log(url.parse(urlString, true).query)
/* 输出 
 * { 
 *  username: 'admin', 
 *  password: '123' 
 * }
 */
复制代码

7 querystring - 解析url模块,多用于得到post请求参数

url须要先引入再使用浏览器

const querystring = require('querystring')
复制代码

7.1 querystring.parse(str)

// 得到前端发送的post请求的参数
const paramsStr = 'username=admin&password=123'
console.log(querystring.parse(paramsStr))
/* 输出 
 * { 
 *  username: 'admin', 
 *  password: '123' 
 * }
 */
复制代码

8 交流

若是这篇文章帮到你了,以为不错的话来点个Star吧。 github.com/lizijie123

相关文章
相关标签/搜索