陈广安个人网站
会写代码的咸鱼
陈广安个人网站阿里云盘资源
陈广安个人网站网盘资源搜索
“ 梦想还是要有的,万一实现了呢!”
— 马云

uniapp使用plus.io进行【创建、写入、读取、删除】文件

创建时间:2025-09-08

队列写入或追加数据文txt文件

// 添加日志写入队列
let logQueue = [];
let isWriting = false;

// 处理日志队列
function processLogQueue() {
  if (isWriting || logQueue.length === 0) return;

  isWriting = true;
  const { fileName, logContent, resolve, reject } = logQueue.shift();

  plus.io.resolveLocalFileSystemURL(
    "_doc/",
    function (entry) {
      entry.getFile(
        fileName,
        { create: true, exclusive: false },
        function (fileEntry) {
          fileEntry.file(
            function (file) {
              const reader = new plus.io.FileReader();
              reader.onloadend = function (e) {
                const existingContent = e.target.result || "";

                fileEntry.createWriter(function (fileWriter) {
                  fileWriter.onwriteend = function () {
                    // console.log("日志写入队列处理完成");
                    resolve("日志写入成功");
                    isWriting = false;
                    processLogQueue(); // 处理下一个队列项
                  };

                  fileWriter.onerror = function (err) {
                    // console.log("文件写入失败", err);
                    reject(`文件写入失败: ${JSON.stringify(err)}`);
                    isWriting = false;
                    processLogQueue();
                  };

                  // 设置文件写入位置为文件开头
                  fileWriter.seek(0);
                  // 写入新内容+现有内容(新内容在前)
                  const newContent =
                    logContent +
                    (existingContent && existingContent.trim() ? "\n" : "") +
                    existingContent;
                  fileWriter.write(newContent);
                });
              };

              // 读取现有文件内容
              reader.readAsText(file, "utf-8");
            },
            function (err) {
              // console.log("获取文件信息失败", err);
              reject(`获取文件信息失败: ${JSON.stringify(err)}`);
              isWriting = false;
              processLogQueue();
            }
          );
        },
        function (err) {
          // console.log("获取文件失败", err);
          reject("获取文件失败: " + JSON.stringify(err));
          isWriting = false;
          processLogQueue();
        }
      );
    },
    function (err) {
      // console.log("解析文件系统路径失败", err);
      reject("获取文件失败: " + JSON.stringify(err));
      isWriting = false;
      processLogQueue();
    }
  );
}

const writeLogToFile = async (fileName, logContent) => {
  // console.log(
  //   "1. writeLogToFile 函数开始执行,参数:fileName=",
  //   fileName,
  //   ", logContent=",
  //   logContent
  // );

  return new Promise((resolve, reject) => {
    // 将日志请求加入队列
    logQueue.push({ fileName, logContent, resolve, reject });
    // console.log("2. 日志请求已加入队列,当前队列长度:", logQueue.length);

    // 开始处理队列
    if (!isWriting) {
      // console.log("3. 开始处理日志队列");
      processLogQueue();
    }
  });
};


读取文件

// 读取日志文件 - 兼容iOS和Android平台
const readLog = (filePath) => {
  return new Promise((resolve, reject) => {
    try {
      // 移除filePath中的_doc/前缀,因为plus.io.resolveLocalFileSystemURL会从_doc/开始解析
      const fileName = filePath.includes("_doc/")
        ? filePath.replace("_doc/", "")
        : filePath;

      console.log(fileName);

      // 使用plus.io.resolveLocalFileSystemURL方式读取文件,这是更通用的跨平台方式
      plus.io.resolveLocalFileSystemURL(
        "_doc/",
        function (entry) {
          entry.getFile(
            fileName,
            { create: false },
            function (fileEntry) {
              fileEntry.file(
                function (file) {
                  const reader = new plus.io.FileReader();
                  reader.onloadend = function (e) {
                    // 成功读取文件内容
                    resolve(e.target.result || "");
                  };
                  reader.onerror = function (err) {
                    reject(`读取文件失败: ${JSON.stringify(err)}`);
                  };
                  // 以UTF-8编码读取文件
                  reader.readAsText(file, "utf-8");
                },
                function (err) {
                  reject(`获取文件信息失败: ${JSON.stringify(err)}`);
                }
              );
            },
            function (err) {
              // 文件不存在的情况
              if (err.code === 1) {
                resolve("日志文件不存在");
              } else {
                reject(`获取文件失败: ${JSON.stringify(err)}`);
              }
            }
          );
        },
        function (err) {
          reject(`解析文件系统路径失败: ${JSON.stringify(err)}`);
        }
      );
    } catch (e) {
      reject(`读取文件异常: ${JSON.stringify(e)}`);
    }
  });
};


删除文件

function delFile(fileName, call) {
  console.log("[delFile] 开始删除文件,文件名:", fileName);

  // 使用plus.io API来删除文件,与其他文件操作函数保持一致
  plus.io.resolveLocalFileSystemURL(
    "_doc/",
    function (entry) {
      console.log("[delFile] 成功解析_doc/路径");

      // 尝试获取要删除的文件
      entry.getFile(
        fileName,
        { create: false },
        function (fileEntry) {
          console.log("[delFile] 成功获取文件,准备删除:", fileName);

          // 执行文件删除操作
          fileEntry.remove(
            function () {
              console.log("[delFile] 文件删除成功:", fileName);
              // 调用回调函数,传入true表示成功
              if (typeof call === "function") {
                call(true);
              }
            },
            function (error) {
              console.error(
                "[delFile] 文件删除失败:",
                fileName,
                "错误:",
                error
              );
              // 调用回调函数,传入false表示失败
              if (typeof call === "function") {
                call(false, error);
              }
            }
          );
        },
        function (error) {
          // 文件不存在的情况(错误码1通常表示文件不存在)
          console.error("[delFile] 获取文件失败:", fileName, "错误:", error);
          if (error.code === 1) {
            console.log("[delFile] 文件不存在:", fileName);
          }
          // 调用回调函数,传入false表示失败
          if (typeof call === "function") {
            call(false, error);
          }
        }
      );
    },
    function (error) {
      console.error("[delFile] 解析_doc/路径失败,错误:", error);
      // 调用回调函数,传入false表示失败
      if (typeof call === "function") {
        call(false, error);
      }
    }
  );
}



调用写入

writeLogToFile(
  "app_log.txt",
  `${dayjs().format("YYYY-MM-DD HH:mm:ss")}\n${url}\n${JSON.stringify(
    data
  )}\n`
);


调用删除

      delFile("app_log.txt", (success, error) => {
        if (success) {
          uni.showToast({
            title: "文件删除成功",
            icon: "none",
          });
          this.$refs.paging.reload();
        } else {
          uni.showToast({
            title: "文件删除失败",
            icon: "none",
          });
          console.error("文件删除失败", error);
        }
      });


调用读取

      readLog("_doc/app_log.txt")
        .then((res) => {
          const arr = res.split("\n");

          let dataList = [];
          // 按照每4行为一组的数据格式解析
          for (let i = 0; i < arr.length - 3; i += 4) {
            if (arr[i]) {
              // 确保时间行不为空
              // console.log(i,arr[i],arr[i+1],arr[i + 2] ? JSON.parse(arr[i + 2]) : null);
              try {
                dataList.push({
                  time: arr[i],
                  url: arr[i + 1],
                  data: arr[i + 2],
                });
              } catch (e) {
                console.warn("解析日志数据出错:", e);
                // 解析错误时仍然添加日志,防止整个解析失败
                dataList.push({
                  time: arr[i],
                  url: arr[i + 1],
                  data: arr[i + 2] || "",
                  parseError: e.message,
                });
              }
            }
          }
          this.length = dataList.length;
          this.$refs.paging.setLocalPaging(dataList);
        })
        .catch((err) => {
          console.warn(err);
        });