Nodejs
# fs模块
引入
const fs = require('fs')
1读文件
fs.readFile(path[,options],callback)
1- 参数1:必选参数,字符串,表示文件的路径
- 参数2:可选参数,表示用什么编码格式读取文件
- 参数3:必选参数,文件读取完成后,通过回调函数拿到读取结果
fs.readFile('./test.txt','utf8',function(err,data){ console.log(data) })
1
2
3写文件
fs.writeFile(file,data[,options],callback)
1- 参数1:必选参数,表示文件的路径的字符串
- 参数2:必选参数,写入的数据内容
- 参数2:可选参数,表示用什么编码格式写入文件,默认值为utf8
- 参数3:必选参数,文件写入完成后的回调函数
fs.writeFile('./note.txt','Hello World!',function(err)=>{ if(err){ return } console.log('写入成功!') })
1
2
3
4
5
6路径拼接问题
以相对路径
./
或../
很容易出现路径动态拼接错误原因:代码运行的时候,会以执行node命令时所处的目录动态拼接被操作文件的完整路径
解决:
- 使用
__dirname
表示当前文件所处的目录
- 使用
# path模块
用来处理路径的模块
路径拼接
path.join()
path.join([...paths]) const base_url = path.join(__dirname,'/index.js') // 输出 当前目录下的index.js文件的路径
1
2
3
4
5获取路径中的文件名
path.basename()
path.basename(path[,ext]) const pathURL = '/a/index.html' const fileName = path.basename(pathURL) // 输出 index.html const fileName = path.basename(pathURL,'.html') // 输出 index
1
2
3
4
5
6
7
8- 参数1:必选参数,表示文件的路径的字符串
- 参数2:可选参数,表示文件扩展名
获取路径中的文件扩展名
path.extname()
path.extname(path) const pathURL = '/a/index.html' const ext = path.extname(pathURL) // 输出 .html
1
2
3
4
5
6
# http模块
用来创建Web服务器的模块
引入
const http = require('http')
1创建Web服务器实例
const server = http.createServer()
1为服务器实例绑定
request
事件req
:Request包含查询字符串、参数、内容、HTTP头部res
:Response表示HTTP响应
server.on('request',(req,res)=>{ console.log('Someone visit our web server.') // 解决中文乱码问题 res.setHeader("Content-Type","text/html;charset=utf8") res.end("你好!") })
1
2
3
4
5
6启动服务器
server.listen(8000, () => { console.log('Server is running at http://127.0.0.1:8000'); })
1
2
3
# 模块化
加载模块
- 使用
require()
加载(可以省略**.js**后缀)
- 使用
向外共享作用域内的数据
export export default model.export 规范 ES6 ES6 commonjs 多个 1个 1个
不要与exports同时使用,指向会有问题导出 export const a = '10'
export const dogSay = function(){}
export function catSay(){}const a = '10'
export default amodule.exports = { a } 导入 import {} from '../xx'
import { a as newA } from './file'import 名称 from '../xx' const { a} = require('./utils')
import { a } from './utils'
编辑 (opens new window)
上次更新: 2024-07-15 23:22:40