zoukankan      html  css  js  c++  java
  • nodeJs--02.fs包文件操作

    fs包文件操作

    • 通过node操作系统中的文件。使用文件系统,需要先引入fs模块,fs模块是核心模块,直接引入不需下载。
    • fs模块中所有操作都有两种 形式可供选择同步和异步。同步文件系统会阻塞程序的执行,也就是除非操作完成,否则不会向下执行代码
    • 一步文件系统不会阻塞程序的执行,而是在操作完成时,通过回调函数将结果返回。

    1.文件写入

    • 写入操作

      • 同步写入:
      var fs = require("fs")
      
      // 1.打开文件
      var fd = fs.openSync("hello.txt","w")
      // path 打开文件路径
      // flags 打开文件操作类型 w 只读,r 写
      // mode 谁文件操作权限,Linux有文件权限
      // 返回值:返回文件描述符
      
      // 2.文件写入
      fs.writeSync(fd, "hello Tom")
      // fd 文件描述符
      // string 要写入内容
      // position 写入起始为止
      // encoding 写入编码, 默认utf-8
      
      // 3.保存关闭文件
      fs.closeSync(fd)
      
      
      • 异步写入
      var fs = require("fs")
      // 异步方法
      // 异步方法都是通过回调函数调用的
      // 回调函数有2个参数:
      //      err  发生错误
      //      fd   文件描述符
      fs.open("hello2.txt", "w", function (err, fd){
          if (!err) {
              console.log(fd)
              // fs.write 异步写入操作
              fs.write(fd, "异步操作", function (err){
                  if (!err) {
                      console.log("异步写入成功")
                  }
                  // 关闭文件
                  fs.close(fd, function (err) {
                      if (!err) {
                          console.log("文件关闭成功")
                      }
                  })
              })
          } else {
              console.log(err)
          }
      })
      
      console.log("程序向下执行")
      // 程序向下执行
      // 20
      // 异步写入成功
      // 文件关闭成功
      
    • 简单异步写入

      var fs = require("fs")
      // fs.writeFile()
      //     path: 要操作文件路径
      //     data: 要写入的数据
      //     options  选项,可以对吸入进行一些设置
      //     callback 当写入完成以后执行的函数
      fs.writeFile("hello3.txt", 'sample write', function (err){
          if (!err) {
              console.log("写入成功")
          }
      })
      
      
    • 追加写入

      fs.writeFile("hello3.txt", 'sample write
      ', {flag: "a"},function (err){
          if (!err) {
              console.log("写入成功")
          }
      })
      
      
    • 流式文件写入

      • 同步,异步,简单文件的写入都不适合打文件写入,性能差,容易内存溢出
      // 创建一个可写入流
      var fs = require("fs");
      
      
      // fs.createWriteStream(path, [options])
      // path:文件路径
      // options 配置参数
      var ws = fs.createWriteStream("hello4.txt")
      
      // 监听流的打开和关闭
      
      // 监听打开为对象绑定一个一次性事件,触发一次失效
      ws.once("open", function (){
          console.log("流文件打开...")
      })
      ws.once("close", function (){
          console.log("流文件关闭...")
      })
      
      ws.write("流失写入1")
      ws.write("流失写入2")
      ws.write("流失写入3")
      ws.write("流失写入4")
      ws.write("流失写入5")
      ws.write("流失写入6")
      
      // 关闭流 此处不能用close
      ws.end();
      

    2.文件读取

    • 简单文件读取

      // fs.readFile(path[, options], callback)
      // path 要读取文件路径
      // options 读取选项
      // callback 回调函数
      fs = require("fs");
      
      
      fs.readFile("./hello4.txt", (err, data) => {
          // throw 触发异常
          if (err) throw err;
          console.log(data)
      })
      
    • 流失文件读取

      var fs = require("fs")
      // 创建读流
      var rs = fs.createReadStream("hello4.txt")
      // 创建写流
      var ws = fs.createWriteStream("hello5.txt")
      
      // 监听打开为对象绑定一个一次性事件,触发一次失效
      rs.once("open", function (){
          console.log("读流文件打开...")
      })
      rs.once("close", function (){
          console.log("读流文件关闭...")
          // 数据读取完毕,关闭流
          ws.end()
      })
      
      ws.once("open", function (){
          console.log("写流文件打开...")
      })
      ws.once("close", function (){
          console.log("写流文件关闭...")
      })
      
      // 读取数据
      rs.on("data", function (data) {
          console.log(data.length)
          // 将读取数据写入
          ws.write(data)
      })
      
      
    • 上述操作过于麻烦,通过pipe简化操作

      var fs = require("fs")
      // 创建读流
      var rs = fs.createReadStream("hello4.txt")
      // 创建写流
      var ws = fs.createWriteStream("hello6.txt")
      
      // 监听打开为对象绑定一个一次性事件,触发一次失效
      rs.once("open", function (){
          console.log("读流文件打开...")
      })
      rs.once("close", function (){
          console.log("读流文件关闭...")
      })
      
      ws.once("open", function (){
          console.log("写流文件打开...")
      })
      ws.once("close", function (){
          console.log("写流文件关闭...")
      })
      // pipe将读流输出到写流
      rs.pipe(ws);
      
      

    3.其他操作

    • 其他操作

      // 验证路径是否存在
      fs.existsSync(path)
      // 获取文件信息
      fs.stat(path,callback)
      fs.statSync(path)
      // 删除文件
      fs.unlink(path,callback)
      fs.unlinkSync(path)
      // 读取文件目录
      fs.readdir(path[,options],callback)
      fs.readdirSync(path,len)
      // 截断文件
      fs.truncate(path, len callback)
      fs.truncateSync(path, len)
      // 建立目录
      fs.mkdir(path[.mode],callback)
      fs.mkdirSync(path[,mode])
      // 文件重命名
      fs.rename(oldpath,newpath,callback)
      fs.renameSync(oldpath,newpath)
      // 删除目录
      fs.rmdir(path,callback)
      fs.rmdirSync(path)
      // 见识文件更改写入
      fs.watchFile(filename[,options],listener)
      
    • fs.stat

      fs.stat("hello.txt", function(err, stat) {
        // 大小
        console.log(stat.size)
        // 是否是一个文件
        console.log(stat.isFile())
        // 是否是文件夹
        console.log(stas.isDirectory())
      })
      
    • fs.readdir

      fs.readdir(".",function (err, files){
          if (!err) {
              console.log(files)
          }
      })
      // files为一个数据,内容为文件名字符串格式
      
    • fs.truncate

      //将文件截断指定大小
      
      fs.truncate("hello2.txt",10,function (err){
          if (err) {
              throw err
          }
          console.log("截取成功")
      })
      
      
    • fs.watchFile

      fs.watchFile("hello2.txt",function (curr,prev) {
          console.log("文件发生变化")
          // curr 当前文件状态
          // prev 修改前文件状态
          console.log("修改前文件大小",prev.size)
          console.log("修改后文件大小",curr.size)
      })
      // 阻塞状态
      

      在options可以设置监听事件间隔

      fs.watchFile("hello2.txt",{interval: 1000},function (curr,prev) {
          console.log("文件发生变化")
          // curr 当前文件状态
          // prev 修改前文件状态
          console.log("修改前文件大小",prev.size)
          console.log("修改后文件大小",curr.size)
      })
      
      
  • 相关阅读:
    Linux 共享库
    使用Visual Studio(VS)开发Qt程序代码提示功能的实现(转)
    ZOJ 3469 Food Delivery(区间DP)
    POJ 2955 Brackets (区间DP)
    HDU 3555 Bomb(数位DP)
    HDU 2089 不要62(数位DP)
    UESTC 1307 windy数(数位DP)
    HDU 4352 XHXJ's LIS(数位DP)
    POJ 3252 Round Numbers(数位DP)
    HDU 2476 String painter (区间DP)
  • 原文地址:https://www.cnblogs.com/xujunkai/p/13661752.html
Copyright © 2011-2022 走看看