文件系统模块,path 路径模块,http模块—Node.js
fs文件系统模块
读取文件
语法格式:
1
| fs.readFile(path[, options], callback)
|
path:文件路径
```
options
1 2 3 4 5 6 7 8
| :配置选项,若是字符串则指定编码格式
- `encoding`:编码格式 - `flag`:打开方式
- ``` callback
|
:回调函数
err:错误信息
data:读取的数据,如果未指定编码格式则返回一个 Buffer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const fs = require('fs')
fs.readFile('./files/1.txt', 'utf-8', function(err, data) => { if(err) { return console.log('failed!' + err.message) } console.log('content:' + data) })
fs.readFile("C:/Users/笔记.mp3", function(err, data) { if(!err) { console.log(data); fs.writeFile("C:/Users/hello.jpg", data, function(err){ if(!err){ console.log("文件写入成功"); } } ); } });
|
写入文件
语法格式:
1
| fs.writeFile(file, data[, options], callback)
|
file:文件路径
data:写入内容
options:配置选项,包含 encoding, mode, flag;若是字符串则指定编码格式
callback:回调函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const fs = require('fs') fs.writeFile('./files/2.txt', 'Hello Nodejs', function (err) { if (err) { return console.log('failed!' + err.message) } console.log('success!') })
fs.writeFile('C:/Users/hello.txt', '通过 writeFile 写入的内容', { flag: 'w' }, function (err) { if (!err) { console.log('写入成功!') } else { console.log(err) } })
|
路径动态拼接问题 __dirname
- 在使用 fs 模块操作文件时,如果提供的操作路径是以
./ 或 ../ 开头的相对路径时,容易出现路径动态拼接错误的问题
- 原因:代码在运行的时候,会以执行 node 命令时所处的目录,动态拼接出被操作文件的完整路径
- 解决方案:在使用 fs 模块操作文件时,直接提供完整的路径,从而防止路径动态拼接的问题
__dirname 获取文件所处的绝对路径
1 2 3
| fs.readFile(__dirname + '/files/1.txt', 'utf8', function(err, data) { ... })
|
path 路径模块
path 模块是 Node.js 官方提供的、用来处理路径的模块。它提供了一系列的方法和属性,用来满足用户对路径的处理需求。
路径拼接 path.join()
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const path = require('path') const fs = require('fs')
const pathStr = path.join('/a', '/b/c', '../../', './d', 'e') console.log(pathStr)
fs.readFile(path.join(__dirname, './files/1.txt'), 'utf8', function (err, dataStr) { if (err) { return console.log(err.message) } console.log(dataStr) })
|
获取路径中文件名 path.basename()
使用 path.basename() 方法,可以获取路径中的最后一部分,常通过该方法获取路径中的文件名
1
| path.basename(path[, ext])
|
1 2 3 4 5 6 7 8 9 10
| const path = require('path')
const fpath = '/a/b/c/index.html'
const fullName = path.basename(fpath) console.log(fullName)
const nameWithoutExt = path.basename(fpath, '.html') console.log(nameWithoutExt)
|
获取路径中的文件扩展名 path.extname()
1 2 3 4 5 6
| const path = require('path')
const fpath = '/a/b/c/index.html'
const fext = path.extname(fpath) console.log(fext)
|
http 模块
http 模块是 Node.js 官方提供的、用来创建 web 服务器的模块。
创建基本 Web 服务器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const http = require('http')
const server = http.createServer()
server.on('request', function (req, res) { const url = req.url const method = req.method const str = `Your request url is ${url}, and request method is ${method}` console.log(str)
res.setHeader('Content-Type', 'text/html; charset=utf-8') res.end(str) })
server.listen(8080, function () { console.log('server running at http://127.0.0.1:8080') })
|