nodejs 拷贝文件、递归拷贝目录、筛选目录下指定文件

目录

文件|目录 存在,可读、可写权限

拷贝文件

递归拷贝目录

递归读取目录 并按照regex筛选出需要的文件路径

完整代码

使用示例

拷贝目录

从目录中筛选指定文件的路径并拷贝到filterPng目录下


文件|目录 存在,可读、可写权限

/**
 * 文件|目录 存在、可读、可写
 * @param path
 * @returns
 */
export function checkExistSync(path: string): boolean {
  try {
    _fs.accessSync(
      path,
      _fs.constants.F_OK | _fs.constants.R_OK | _fs.constants.W_OK
    );
    // console.log(`Directory "${path}" exists.`);
    return true;
  } catch (err) {
    console.log(`Directory "${path}" does not exist.`);
    return false;
  }
}
常量描述
F_OK指示文件对调用进程可见的标志。 这对于确定文件是否存在很有用,但没有说明 rwx 权限。 未指定模式时的默认值。
R_OK指示文件可以被调用进程读取的标志。
W_OK指示文件可以被调用进程写入的标志。
X_OK指示文件可以被调用进程执行的标志。 这在 Windows 上不起作用(行为类似于 fs.constants.F_OK)。

拷贝文件

/**
 * 拷贝文件
 * @param source
 * @param destination
 * @returns
 */
export async function copyFile(
  srcPath: string,
  desPath: string
): Promise<string> {
  return new Promise((resolve, reject) => {
    try {
      const writeStream = _fs.createWriteStream(desPath);
      const readStream = _fs.createReadStream(srcPath);
      readStream.on("error", reject);
      readStream.on("close", resolve);
      writeStream.on("error", reject);
      writeStream.on("finish", () => {
        console.log("File copied successfully!");
      });
      //将原文件流导向目标文件流
      readStream.pipe(writeStream);
    } catch (error) {
      console.error(error);
    }
  });
}

递归拷贝目录

/**
 * 递归拷贝目录
 * @param source
 * @param destination
 */
export async function copyDirectory(srcPath: string, desPath: string) {
  try {
    const isSrcExist = checkExistSync(srcPath);
    if (!isSrcExist) _fs.ensureDirSync(srcPath);
    const isDesExist = checkExistSync(desPath);
    if (!isDesExist) _fs.ensureDirSync(desPath);
    // 读取源目录中的所有文件和子目录
    const files = await _fs.readdir(srcPath);
    for (const file of files) {
      const copyPath = _path.join(srcPath, file);
      const destPath = _path.join(desPath, file);
      const stats = await _fs.stat(copyPath);
      if (stats.isDirectory()) {
        // 如果是子目录,递归拷贝
        await copyDirectory(copyPath, destPath);
      } else {
        // 如果是文件,直接拷贝
        await copyFile(copyPath, destPath);
      }
    }
    // console.log(`Directory copied successfully from ${srcPath} to ${desPath}`);
  } catch (error: any) {
    console.error(`Error copying directory: ${error.message}`);
  }
}

递归读取目录 并按照regex筛选出需要的文件路径

/**
 * 递归读取目录 并按照regex筛选出需要的文件路径
 * @param dirPath
 * @param regex
 * @returns
 */
export async function readDirRecursively(
  dirPath: string,
  regex: RegExp
): Promise<string[]> {
  const filter: string[] = [];
  const files = await _fs.readdir(dirPath);
  for (const file of files) {
    const tempPath = _path.resolve(dirPath, file);
    const stat = await _fs.stat(tempPath);
    if (stat.isDirectory()) {
      const tempFilter = await readDirRecursively(tempPath, regex);
      filter.push(...tempFilter);
    } else if (stat.isFile()) {
      const extname = _path.basename(tempPath);
      if (regex.test(extname)) {
        filter.push(tempPath);
      }
    }
  }
  return filter;
}

完整代码

import * as _fs from "fs-extra";
import * as _path from "path";

/**
 * 文件|目录 存在、可读、可写
 * @param path
 * @returns
 */
export function checkExistSync(path: string): boolean {
  try {
    _fs.accessSync(
      path,
      _fs.constants.F_OK | _fs.constants.R_OK | _fs.constants.W_OK
    );
    return true;
  } catch (err) {
    return false;
  }
}
/**
 * 递归读取目录 并按照regex筛选出需要的文件路径
 * @param dirPath
 * @param regex
 * @returns
 */
export async function readDirRecursively(
  dirPath: string,
  regex: RegExp
): Promise<string[]> {
  const filter: string[] = [];
  const files = await _fs.readdir(dirPath);
  for (const file of files) {
    const tempPath = _path.resolve(dirPath, file);
    const stat = await _fs.stat(tempPath);
    if (stat.isDirectory()) {
      const tempFilter = await readDirRecursively(tempPath, regex);
      filter.push(...tempFilter);
    } else if (stat.isFile()) {
      const extname = _path.basename(tempPath);
      if (regex.test(extname)) {
        filter.push(tempPath);
      }
    }
  }
  return filter;
}

/**
 * 拷贝文件
 * @param source
 * @param destination
 * @returns
 */
export async function copyFile(
  srcPath: string,
  desPath: string
): Promise<string> {
  return new Promise((resolve, reject) => {
    try {
      const writeStream = _fs.createWriteStream(desPath);
      const readStream = _fs.createReadStream(srcPath);
      readStream.on("error", reject);
      readStream.on("close", resolve);
      writeStream.on("error", reject);
      writeStream.on("finish", () => {
        console.log("File copied successfully!");
      });
      //将原文件流导向目标文件流
      readStream.pipe(writeStream);
    } catch (error) {
      console.error(error);
    }
  });
}

/**
 * 递归拷贝目录
 * @param source
 * @param destination
 */
export async function copyDirectory(srcPath: string, desPath: string) {
  try {
    const isSrcExist = checkExistSync(srcPath);
    if (!isSrcExist) _fs.ensureDirSync(srcPath);
    const isDesExist = checkExistSync(desPath);
    if (!isDesExist) _fs.ensureDirSync(desPath);
    // 读取源目录中的所有文件和子目录
    const files = await _fs.readdir(srcPath);
    for (const file of files) {
      const copyPath = _path.join(srcPath, file);
      const destPath = _path.join(desPath, file);
      const stats = await _fs.stat(copyPath);
      if (stats.isDirectory()) {
        // 如果是子目录,递归拷贝
        await copyDirectory(copyPath, destPath);
      } else {
        // 如果是文件,直接拷贝
        await copyFile(copyPath, destPath);
      }
    }
    // console.log(`Directory copied successfully from ${srcPath} to ${desPath}`);
  } catch (error: any) {
    console.error(`Error copying directory: ${error.message}`);
  }
}

使用示例

拷贝目录

const srcPath = "/Users/leiming/cocos/shader/shader2x";
const desPath = "/Users/leiming/cocos/shader/copyShader2x";
await copyDirectory(srcPath, desPath);

从目录中筛选指定文件的路径并拷贝到filterPng目录下

 //找到shader2x 目录中的所有png 图片地址
  const dirPath = "/Users/leiming/cocos/shader/shader2x";
  const files = await filterFilesInDirByRegex(dirPath, /\.png$/);
  console.log(files);

  //把png图片拷贝到filterPng目录下
  const desPath = "/Users/leiming/cocos/shader/filterPng";
  _fs.ensureDirSync(desPath);
  for (const file of files) {
    const desFilePath = _path.resolve(desPath, _path.basename(file));
    await copyFile(file, desFilePath);
  }

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
在Node.js中,你可以使用`fs`模块来复制文件指定目录。下面是一个简单的示例代码: ```javascript const fs = require('fs'); const path = require('path'); function copyFile(sourcePath, targetPath) { // 构造目标文件路径 const fileName = path.basename(sourcePath); const targetFilePath = path.join(targetPath, fileName); // 创建可读流和可写流 const readStream = fs.createReadStream(sourcePath); const writeStream = fs.createWriteStream(targetFilePath); // 执行文件复制 readStream.pipe(writeStream); // 监听复制完成事件 writeStream.on('finish', () => { console.log('文件复制成功!'); }); // 监听错误事件 writeStream.on('error', (err) => { console.error('文件复制失败:', err); }); } // 使用示例 const sourcePath = '/path/to/source/file.txt'; const targetPath = '/path/to/target/directory'; copyFile(sourcePath, targetPath); ``` 上述代码中,我们首先引入了`fs`和`path`模块。然后定义了一个`copyFile`函数,该函数接受源文件路径和目标目录路径作为参数。 在函数内部,我们使用`path.basename`方法获取源文件文件名,并使用`path.join`方法构造目标文件的完整路径。 接下来,我们使用`fs.createReadStream`创建一个可读流,用于读取源文件的内容。同时,使用`fs.createWriteStream`创建一个可写流,用于将内容写入目标文件。 然后,我们使用`readStream.pipe(writeStream)`将可读流的内容传输到可写流中,实现文件的复制。 最后,我们监听可写流的`finish`事件,表示文件复制完成。如果复制过程中发生错误,我们监听可写流的`error`事件,并打印错误信息。 你可以根据实际情况修改源文件路径和目标目录路径,然后调用`copyFile`函数进行文件复制。
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值