fs文件系统模块

145 阅读4分钟

初识 Nodejs

  • 基于 Express 框架 (opens new window),可以快速构建 Web 应用
  • 基于 Electron 框架 (opens new window),可以构建跨平台的桌面应用
  • 基于 restify 框架 (opens new window),可以快速构建 API 接口项目
  • 读写和操作数据库、创建实用的命令行工具辅助前端开发、etc…

fs文件系统模块

  • ==读取文件==
fs.readFile(path[, options], callback)
  • path:文件路径
  • options:配置选项,若是字符串则指定编码格式
  • encoding:编码格式
  • flag:打开方式
  • callback:回调函数
  • err:错误信息
  • data:读取的数据,如果未指定编码格式则返回一个 Buffer
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);
		// 将data写入到文件中
		fs.writeFile("C:/Users/hello.jpg", data, function(err){
			if(!err){
				console.log("文件写入成功");
			}
		} );
	}
});
  • ==写入文件==
fs.writeFile(file, data[, options], callback)
  • file:文件路径
  • data:写入内容
  • options:配置选项,包含 encoding, mode, flag;若是字符串则指定编码格式
  • callback:回调函数
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)
  }
})

考试成绩整理案例

//1.导入fs文件系统模块
const fs = require('fs')

//2.读取考试成绩内容
fs.readFile('../files/考试成绩信息.txt', 'utf8' , function(err, data){
    if(err){
        return console.log('文件读取失败,' + err.message)
    }
    console.log('文件读取成功内容是' + data)
    //对读取的内容格式进行整理
    //1.使用空格进行分割
    const arrOld = data.split(' ')
    // console.log(arrOld)
    //2.循环分割后的数组对每一项数据进行字符串的替换
    let arrNew = []
    arrOld.forEach((item)=>{arrNew.push(item.replace('=' , ':'))})
    // console.log(arrNew)
    //3.把數組中的每一項進行合併得到一個新的子婦串
   const newStr =  arrNew.join('\r\n')
//    console.log(newStr)
    //4.將處理好的数据写入到文件中
    fs.writeFile('../考试成绩信息', newStr, function(err){
        if (err) {return console.error('文件写入失败' + err.message)}
        console.log('文件写入成功', newStr)
    })
})

路径动态拼接问题 __dirname

  • 在使用 fs 模块操作文件时,如果提供的操作路径是以 ./ 或 ../ 开头的相对路径时,容易出现路径动态拼接错误的问题
  • 原因:代码在运行的时候,会以执行 node 命令时所处的目录,动态拼接出被操作文件的完整路径
  • 解决方案:在使用 fs 模块操作文件时,直接提供完整的路径,从而防止路径动态拼接的问题
  • __dirname 获取文件所处的绝对路径 == 当前页面所处的目录
fs.readFile(__dirname + '/files/1.txt', 'utf8', function(err, data) {
  ...
})

其他文件操作命令

验证路径是否存在

  • fs.exists(path, callback)
  • fs.existsSync(path)

获取文件信息:

  • fs.stat(path, callback)
  • fs.stat(path)

删除文件

  • fs.unlink(path, callback)
  • fs.unlinkSync(path)

列出文件:

  • fs.readdir(path[,options], callback)
  • fs.readdirSync(path[, options])

截断文件:

  • fs.truncate(path, len, callback)
  • fs.truncateSync(path, len)

建立目录:

  • fs.mkdir(path[, mode], callback)
  • fs.mkdirSync(path[, mode])

删除目录:

  • fs.rmdir(path, callback)
  • fs.rmdirSync(path)

重命名文件和目录:

  • fs.rename(oldPath, newPath, callback)
  • fs.renameSync(oldPath, newPath)

监视文件更改:

  • fs.watchFile(filename[, options], listener)

path 路径模块

==路径拼接 path.join()==

path 模块是 Node.js 官方提供的、用来处理路径的模块。它提供了一系列的方法和属性,用来满足用户对路径的处理需求。

const path = require('path')
const fs = require('fs')

// 注意 ../ 会抵消前面的路径
// ./ 会被忽略
const pathStr = path.join('/a', '/b/c', '../../', './d', 'e')
console.log(pathStr) // \a\d\e

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() 方法,可以获取路径中的最后一部分,常通过该方法获取路径中的文件名

  • path: 文件路径 必填
  • ext: 文件扩展名 可省略
path.basename(path[, ext])

==获取路径中文件扩展名 path.extname()==

  • path: 文件路径 必填
const path = require('path')

const fpath = '/a/b/c/index.html'

const fext = path.extname(fpath)
console.log(fext) // .html

时钟案例

// 导入fs path 模块
const fs = require('fs')
const path = require('path')

//定义正则表达式 分别匹配 <style></style> 和 <script></style>

const regStyle = /<style>[\s\S]*<\/style>/ 

const regScript = /<script>[\s\S]*<\/script>/


//读取需要被处理的index.html文件
const pathStr = path.join(__dirname , '/index.html')

fs.readFile(pathStr, 'utf8', function(err, data){
    if(err){
        return console.log('文件读取失败' + err.message)
    }
    console.log('文件读取成功' + data)

   //读取成功后调用对应的方法解构出css 和script 结构
   resolveCSS(data)
   resolveJS(data)
   resolveHtml(data) 
});


//定义处理CSS样式的处理方法
function resolveCSS(htmlStr){
    //使用正则提取符合的内容
    const r1 = regStyle.exec(htmlStr);
   const newCss =  r1[0].replace('<style>', '').replace('</style>' , '')
//    console.log(newCss);
   //将css样式写入到index.css中
   fs.writeFile(path.join(__dirname, "/index.css"), newCss, function(err){
    if(err){
        console.log('文件写入失败' + err.message)
    }
    console.log('文件写入成功')
   });
}

//定义处理js的方法
function resolveJS(htmlStr){
    //调用正则的exec方法获取数据
  const r2 = regScript.exec(htmlStr);
//   console.log(r1)  
 const NewJs =  r2[0].replace('<script>', '').replace('</script>', '')
//  console.log(NewJs);
//将文件写入index.js中
fs.writeFile(path.join(__dirname, '/index.js'), NewJs, function(err){
    if(err){
        console.log('文件写入失败' + err.message)
    }
    console.log('文件写入成功')
})
}





//定义处理html结构的方法
function resolveHtml(htmlStr) {
    //调用replace方法
  const newHtml =   htmlStr
      .replace(regStyle, '<link rel="stylesheet" href="./index.css">')
      .replace(regScript, '<script src="./index.js"></script>')
  //將替換後的html代碼写入到index.html中
  fs.writeFile(path.join(__dirname, "./index.html"), newHtml, function (err) {
    if (err) {
        console.log('文件写入失败' + err.message)
    }
    console.log('文件写入成功')
  })
}