注意:在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 "color: #ff0000">对文件夹(目录)的操作

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

复制文件夹

使用了两种方式:

  • 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参考: https://github.com/jprichardson/node-fs-extra
 */

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…

总结

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

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。