前端node获取项目中所有符合正则的文件id

107 阅读1分钟

由于项目需要做前端之前上传过的文件与图片进行迁移,而所有的文件图片都是以文件id进行回显。所以可以借助node,获取项目中符合19位数字正则的文件id。

const fs = require("fs");
const path = require("path");

// 正则表达式用于匹配19位数字的 fileID
const fileIdRegex = /\b(\d{19})\b/g;

// 文件夹路径
const folderPath = "D:/项目目录";

const previewUrl = "https://baidu.com/preview/";
const downloadUrl = "https://baidu.com/download/";

// 获取某个目录下符合正则的文件
function getAllFilesMatchingRegex(dir, regex, fileList = []) {
  const files = fs.readdirSync(dir);
  files.forEach((file) => {
    const filePath = path.join(dir, file);
    const stats = fs.statSync(filePath);
    if (stats.isDirectory()) {
      fileList = getAllFilesMatchingRegex(filePath, regex, fileList);
    } else if (stats.isFile()) {
      let data = fs.readFileSync(filePath, "utf8");
      const fileIds = data.match(fileIdRegex);
      if (!fileIds) return;
      fileIds.forEach((fileID) => {
        // 存储文件路径和对应的 fileID
        // fileList.push({
        //   filePath: filePath,  // 文件地址
        //   fileId: fileID,  // 文件id
        //   downloadPath: downloadUrl + fileID,  // 文件下载地址
        //   previewPath: previewUrl + fileID,  // 文件地址
        // });
        fileList.push(fileID)
      });
    }
  });
  return fileList;
}

const filePathsAndIds = getAllFilesMatchingRegex(folderPath, fileIdRegex);
console.log(filePathsAndIds);  // 打印出来所有文件id

// 将内容写入js文件
fs.writeFileSync('./fileids.js', JSON.stringify(filePathsAndIds), {encoding: 'utf-8'})