Node.js是JavaScript运行环境
①浏览器是JavaScript的前端运行环境;
②Node.js是JavaScript的后端运行环境;
③Node.js中无法调用DOM和BOM等浏览器内置API
fs文件系统模块
fs模块是Node.js官方提供的、用来操作文件的模块。提供了一系列的方法和属性,用来满足用户对文件的操作需求。
如果要在JavaScript代码中,使用fs模块来操作文件,则需要使用如下的方式先导入它:const fs = require('fs')
读取文件
①fs.readFile()
方法,可以读取指定文件中的内容,语法格式如下:
fs.readFile(path[, options], callback)
path:必选参数,字符串,表示文件的路径
options:可选参数,表示以什么编码格式来读取文件
callback:必选参数,文件读取完成后,通过回调函数拿到读取结果
//1. 导入fs模块,来操作文件
const fs = require('fs')
// 2.调用fs.readFile()方法读取文件
// 参数1:读取文件的存放路径
// 参数2:读取文件时采用的编码格式,一般默认指定 utf8
// 参数3:回调函数,拿到读取失败和成功的结果 err dataStr
fs.readFile('./files/1.txt', 'utf8', function (err, dataStr) {
// 2.1打印失败的结果
//如果读取成功,则err的值为null
//如果读取失败,则err的值为 错位对象, dataStr 的值为undefined
console.log(err)
console.log('------')
//2.2打印成功的结果
console.log(dataStr)
})
②判断文件是否读取成功
通过判断err对象是否为null
//判断文件是否读取成功
const fs = require('fs') //导入fs模块
fs.readFile('./files/1.txt', 'utf8', function (err, dataStr) {//注意function选对
if (err) {
return console.log('读取文件失败' + err.message)
}
console.log('读取成功' + dataStr)
})
写入文件
①fs.writeFile(file, data[, options], callback )
参数一:必选,文件路径字符串,文件存放路径
参数二:必选,写入的内容
参数三:可选,表示以什么格式写入文件内容(默认utf8)
参数四:必选,文件写入完成后的回调函数
//1.导入 fs 文件系统文件
const fs = require('fs')
//2. 调用 fs.writeFile() 方法, 写入文件的内容
// 参数1:表示文件的存放路径
// 参数2:表示要写入的内容
// 参数3: 回调函数
fs.writeFile('./files/2.txt', 'abcd', function (err) {
//2.1 如果文件写入成功, 则err的值等于 null
//2.2 如果文件写入失败, 则err的值等于一个 错误对象
console.log(err)
})
②判断文件是否写入成功
const fs = require('fs')
fs.writeFile('./files/2.txt', 'abcd', function (err) {
if (err) {
return console.log('文件写入失败' + err.message)
}
console.log('文件写入成功')
})
案例:处理成绩
成绩.txt
小红=99 小白=100 小黄=70 小黑=66 小绿=88
04_整理成绩.js
//1.导入 fs 模块
const fs = require('fs')
// 2.调用 fs.resdFile() 读取文件的内容
fs.readFile('./files/成绩.txt', 'utf8', function (err, dataStr) {
// 3.判断是否读取成功
if (err) {
return console.log('读取文件失败' + err.message)
}
// console.log('读取文件成功' + dataStr)
//4.1 先按空格进行分隔
const arrOld = dataStr.split(' ')
console.log(arrOld)
//4.2 循环分割后的数组,对每一项数据,进行字符串的替换操作
const arrNew = []
arrOld.forEach(item => {
arrNew.push(item.replace('=', ': '))
});
//4.3 把新数组中的每一项,进行合并,得到一个新的字符串
const newStr = arrNew.join('\r\n') //回车换行
console.log(newStr)
//5. 调用 fs.writeFile() 方法,把处理完毕的成绩,写入到新文件中
fs.writeFile('./files/成绩-ok.txt', newStr, function (err) {
if (err) {
return console.log('写入文件失败' + err.message)
}
console.log('写入成功')
})
})
输出:
路径拼接问题
在使用fs模块操作文件时,如果提供的操作路径时以
./
或../
开头的相对路径时,容易出现路径动态拼接错误
解决方法
法一:
①改为绝对路径(完整文件存放路径)
②由于js中一个\
表示转义字符,所以\
用\\
表示
eg:C:\\Users\\lyh\\Desktop\\node.js\\day01\\files
③但是移植性差,不利于维护
法二:
__dirname
表示当前文件所处的目录
const fs = require('fs')
/*fs.readFile('./files/1.txt', 'utf8', function (err, dataStr) {
if (err) {
console.log('读取失败' + err.message);
}
console.log('读取成功' + dataStr)
})*/
fs.readFile(__dirname + '/files/1.txt', 'utf8', function (err, dataStr) {
if (err) {
console.log('读取失败' + err.message);
}
console.log('读取成功' + dataStr)
})
path路径模块
导入path
const path = require('path')
①path.join()
:将多个路径片段拼接成一个完整的路径字符串
语法:path.join([...paths])
const pathStr = path.join('/a', '/b/c', '../', './d', 'e')
console.log(pathStr)//输出 \a\b\d\e( '../'抵消一个路径, ./不抵消)
const pathStr = path.join(__dirname, './files/1.txt')//凡是涉及到路径拼接不用 +,用path.join()
console.log(pathStr)//输出 当前文件所处目录\files\1.txt
获取路径的文件名
path.basename()
从路径字符串中,将文件名解析出来
语法:path.basename(path [, ext])
path :必选,路径的字符串
ext:文件的扩展名
const path = require('path')
//定义文件的存放路径
const fpath = '/a/b/c/index.html'
const fullName = path.basename(fpath)
console.log(fullName)//返回 index.html
//不打印后缀名
const nameWithoutExit= path.basename(fpath, 'html')
console.log(nameWithoutExit)//返回 index
获取路径的文件扩展名
path.extname(path)
const fpath = 'a/b/c/index.html'//路径字符串
const fext =path.extname(fpath)
console.log(fext)//输出 .html
时钟案例
实现功能:将一个index.html文件拆分:index.css、index.js、index.html,将其存放在clock目录中
实现步骤:
① 创建两个正则表达式,分别匹配 < style > 和 < script > 标签;
② 使用fs模块,读取需要被处理的HTML文件 ;
③ 自定义resolveCSS、resolveJS、resolveHTML方法,写入文件;
//1.1 导入 fs 文件系统模块
const fs = require('fs')
//1.2 导入 path 路径处理模块
const path = require('path')
//1.3 匹配< style ></ style > 标签的正则
// 其中 \s 表示非空白字符; * 表示匹配任意次
const regStyle = /<style>[\s\S]*<\/style>/ /*加一个‘\’ 用以转义 */
//1.4 匹配< script > </ script > 标签的正则
const regScript = /<script>[\s\S]*<\/script>/
//2.1调用 fs.readFile()方法读取文件
fs.readFile(path.join(__dirname, './files/index.html'), 'utf8', function (err, dataStr) {
//2.2 读取 HTML 文件失败
if (err) {
return console.log("读取失败" + err.message)
}
//2.3 读取文件成功后,调用对应的三个方法,分别拆解出 css, js, html文件
resolveCSS(dataStr)
resolveJS(dataStr)
resolveHTML(dataStr)
})
//3.1 定义处理 css 样式的方法
function resolveCSS(htmlStr) {
//3.2 使用正则提取需要的内容
const r1 = regStyle.exec(htmlStr)
// console.log(newCSS)
//3.3将提出来的样式字符串,进行字符串的 replace 替换操作
const newCSS = r1[0].replace('<style>', '').replace('</style>', '')
// console.log(newCSS)
//3.4调用fs。writeFIle()方法,将提取的样式,写入到clock目录中 index.css文件里面
fs.writeFile(path.join(__dirname, './clock/index.css'), newCSS, function (err) {
if (err) {
return console.log('写入失败' + err.message)
}
console.log('CSS成功')
})
}
//4.1 定义处理 js 脚本的方法
function resolveJS(htmlStr) {
//3.2 使用正则提取需要的内容
const r2 = regScript.exec(htmlStr)
// console.log(newJS)
//3.3将提出来的样式字符串,进行字符串的 replace 替换操作
const newJS = r2[0].replace('<script>', '').replace('</script>', '')
// console.log(newJS)
//3.4调用fs。writeFIle()方法,将提取的样式,写入到clock目录中 index.js文件里面
fs.writeFile(path.join(__dirname, './clock/index.js'), newJS, function (err) {
if (err) {
return console.log('写入失败' + err.message)
}
console.log('JS成功')
})
}
//5.1 定义处理 HTML 结构的方法
function resolveHTML(htmlStr) {
//5.2 将字符串调用 replace 方法, 将内嵌的 style 和 script 标签, 替换为外联的 link 和 script 标签
const newHTML = htmlStr.replace(regStyle, '<link rel = "stylesheet" href="./index.css" />').replace(regScript, '<script src="./index.js"></script>')
//5.3 写入index》html 这个文件
fs.writeFile(path.join(__dirname, './clock/index.html'), newHTML, function (err) {
if (err) {
return console.log('写入失败' + err.message)
}
console.log('HTML成功')
})
}