用户登录
用户注册

分享至

node删除、复制文件或文件夹示例代码

  • 作者: 段子男神哈奇士
  • 来源: 51数据库
  • 2021-08-17

注意:在win10,v10.16.1 环境运行无问题

首先引入相关包(会在使用处具体说明):

const fs = require('fs')
const path = require('path')
const child_process = require('child_process')
const fsex = require('fs-extra')
/**
 * @des 该包为实验性api
 */
const fspromises = require('fs').promises

对文件的操作

复制文件

这里列出三种方式:

  1. 使用 writefilesync 和 readfilesync 结合
  2. 使用 copyfilesync
  3. 使用promises的copyfile方法

其中的同步或异步方法可酌情更改,实现代码如下

/**
 * @param { copiedpath: string } (被复制文件的地址,相对地址)
 * @param { resultpath: string } (放置复制文件的地址,相对地址)
 */
function copyfile(copiedpath, resultpath) {
 copiedpath = path.join(__dirname, copiedpath)
 resultpath = path.join(__dirname, resultpath)

 try {
  /**
   * @des 方式一
   */
  // fs.writefilesync(resultpath, fs.readfilesync(copiedpath))
  /**
   * @des 方式二
   */
  // fs.copyfilesync(copiedpath, resultpath)
  console.log('success');
 } catch (error) {
  console.log(error);
 }
 /**
  * @des 方式三
  */
 fspromises.copyfile(copiedpath, resultpath)
  .then(() => {
   console.log('success');
  }).catch((err) => {
   console.log(err);
  });
}

删除文件

使用 unlinksync 方法,实现代码如下

/**
 * @param { delpath:string } (需要删除文件的地址)
 * @param { direct:boolean } (是否需要处理地址)
 */
function deletefile(delpath, direct) {
 delpath = direct ? delpath : path.join(__dirname, delpath)
 try {
  /**
   * @des 判断文件或文件夹是否存在
   */
  if (fs.existssync(delpath)) {
   fs.unlinksync(delpath);
  } else {
   console.log('inexistence path:', delpath);
  }
 } catch (error) {
  console.log('del error', error);
 }
}

对文件夹(目录)的操作

以下代码有引用,复制文件相关方法

复制文件夹

使用了两种方式:

  • child_process
  • 递归的读取文件和文件夹再在指定地址创建

实现代码和释意如下:

/**
 * @des 参数解释同上
 */
function copyfolder(copiedpath, resultpath, direct) {
  if(!direct) {
    copiedpath = path.join(__dirname, copiedpath)
    resultpath = path.join(__dirname, resultpath)
  }

  function createdir (dirpath) {
    fs.mkdirsync(dirpath)    
  }

  if (fs.existssync(copiedpath)) {
    createdir(resultpath)
    /**
     * @des 方式一:利用子进程操作命令行方式
     */
    // child_process.spawn('cp', ['-r', copiedpath, resultpath])

    /**
     * @des 方式二:
     */
    const files = fs.readdirsync(copiedpath, { withfiletypes: true });
    for (let i = 0; i < files.length; i++) {
      const cf = files[i]
      const ccp = path.join(copiedpath, cf.name)
      const crp = path.join(resultpath, cf.name) 
      if (cf.isfile()) {
        /**
         * @des 创建文件,使用流的形式可以读写大文件
         */
        const readstream = fs.createreadstream(ccp)
        const writestream = fs.createwritestream(crp)
        readstream.pipe(writestream)
      } else {
        try {
          /**
           * @des 判断读(r_ok | w_ok)写权限
           */
          fs.accesssync(path.join(crp, '..'), fs.constants.w_ok)
          copyfolder(ccp, crp, true)
        } catch (error) {
          console.log('folder write error:', error);
        }

      }
    }
  } else {
    console.log('do not exist path: ', copiedpath);
  }
}

删除文件夹

递归文件和文件夹,逐个删除

实现代码如下:

function deletefolder(delpath) {
  delpath = path.join(__dirname, delpath)

  try {
    if (fs.existssync(delpath)) {
      const delfn = function (address) {
        const files = fs.readdirsync(address)
        for (let i = 0; i < files.length; i++) {
          const dirpath = path.join(address, files[i])
          if (fs.statsync(dirpath).isdirectory()) {
            delfn(dirpath)
          } else {
            deletefile(dirpath, true)
          }
        }
        /**
        * @des 只能删空文件夹
        */
        fs.rmdirsync(address);
      }
      delfn(delpath);
    } else {
      console.log('do not exist: ', delpath);
    }
  } catch (error) {
    console.log('del folder error', error);
  }
}

执行示例

目录结构

|- index.js(主要执行代码)
|- a
    |- a.txt
    |- b.txt
|- c
    |- a.txt
    |- b.txt
|- p
    |- a.txt
    |- b.txt

根据传入的参数不同,执行相应的方法

/**
 * @des 获取命令行传递的参数
 */
const type = process.argv[2]

function execute() {
  /**
   * @des 请根据不同的条件传递参数
   */
  if (type === 'copyfile') {
    copyfile('./p/a.txt', './c/k.txt')
  }

  if (type === 'copyfolder') {
    copyfolder('./p', './a')
  }

  if (type === 'delfile') {
    deletefile('./c/ss.txt')
  }

  if (type === 'delfolder') {
    deletefolder('./a')
  }
}

execute()

命令行传参数

/**
 * @des 命令行传参
 * 执行 node ./xxx/index.js 111 222
 * 输出:
 * 0: c:\program files\nodejs\node.exe
 * 1: g:\github\xxx\xxxx\index.js
 * 2: 111
 * 3: 222
 */
process.argv.foreach((val, index) => {
  console.log(`${index}: ${val}`);
});

利用 fs-extra 实现

这是对fs相关方法的封装,使用更简单快捷

/**
 * @des fs-extra 包实现
 * api参考: http://www.51sjk.com/Upload/Articles/1/0/268/268557_20210708023942471.jpg
 */

function fsextra() {
  async function copy() {
    try {
      await fsex.copy(path.join(__dirname + '/p'), path.join(__dirname + '/d'))
      console.log('success');
    } catch (error) {
      console.log(error);
    }
  }

  copy()
}

可执行源码: github.com/namehewei/n…

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。

软件
前端设计
程序设计
Java相关