- Node.js 的学习路径:
JavaScript 基础语法 + Node.js 内置 API 模块(fs、path、http等)+ 第三方 API 模块(express、mysql 等)
- node 终端使用的快捷键
① 使用 ↑ 键,可以快速定位到上一次执行的命令
② 使用 tab 键,能够快速补全路径
③ 使用 esc 键,能够快速清空当前已输入的命令
④ 输入 cls 命令,可以清空终端
fs 文件系统模块
const fs = require('fs')
⚫ fs.readFile() 方法,用来读取指定文件中的内容
fs.readFile(path,options(utf8),callback)
参数1:必选参数,字符串,表示文件的路径。
参数2:可选参数,表示以什么编码格式来读取文件。
参数3:必选参数,文件读取完成后,通过回调函数拿到读取的结果。
fs.readFile('./files/11.txt',"utf8",function(err,dataStr){
if (err) {
return console.log('读取文件失败!' + err.message)
}
console.log('读取文件成功!' + dataStr)
})
⚫ fs.writeFile() 方法,用来向指定的文件中写入内容
fs.writeFile(file,data,options,callback)
参数1:必选参数,需要指定一个文件路径的字符串,表示文件的存放路径。
参数2:必选参数,表示要**写入的内容*
参数3:可选参数,表示以什么格式写入文件内容,*默认值是 utf8*
参数4:必选参数,文件写入完成后的*回调函数*
fs.writeFile('./files/2.txt', 'Hello Node.js', function(err) {
if (err) {
return console.log('文件写入失败!' + err.message)
}
console.log('文件写入成功!')
})
⚫ path 路径模块
path.join() 方法,用来将多个路径片段拼接成一个完整的路径字符串
path.basename() 方法,用来从路径字符串中,将文件名解析出来
const path = require('path')
⚫ 路径拼接
path.join() 方法,可以把多个路径片段拼接为完整的路径字符串:
const pathStr = path.join('/a', '/b/c', '../../', './d', 'e')
console.log(pathStr) // \a\b\d\e
常用的路径拼接方式是__dirname
const pathStr2= fs.readFile(__dirname + '/files/1.txt')
console.log(pathStr2)
⚫ 获取路径中的文件名
path.basename(path,ext) 的语法格式
参数1:path <string> 必选参数,表示一个路径的字符串
参数2:ext <string> 可选参数,表示文件扩展名
返回: <string> 表示路径中的最后一部分
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(path) 的语法格式
const path = require('path')
// 这是文件的存放路径
const fpath = '/a/b/c/index.html'
const fext = path.extname(fpath)
console.log(fext)