栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

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

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

const fs = require('fs')
const path = require('path')
const child_process = require('child_process')
const fsEx = require('fs-extra')

const fsPromises = require('fs').promises

对文件的操作

复制文件

这里列出三种方式:

  1. 使用 writeFileSync 和 readFileSync 结合
  2. 使用 copyFileSync
  3. 使用promises的copyFile方法

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


function copyFile(copiedPath, resultPath) {
 copiedPath = path.join(__dirname, copiedPath)
 resultPath = path.join(__dirname, resultPath)

 try {
  
  // fs.writeFileSync(resultPath, fs.readFileSync(copiedPath))
  
  // fs.copyFileSync(copiedPath, resultPath)
  console.log('success');
 } catch (error) {
  console.log(error);
 }
 
 fsPromises.copyFile(copiedPath, resultPath)
  .then(() => {
   console.log('success');
  }).catch((err) => {
   console.log(err);
  });
}

删除文件

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


function deleteFile(delPath, direct) {
 delPath = direct ? delPath : path.join(__dirname, delPath)
 try {
  
  if (fs.existsSync(delPath)) {
   fs.unlinkSync(delPath);
  } else {
   console.log('inexistence path:', delPath);
  }
 } catch (error) {
  console.log('del error', error);
 }
}

对文件夹(目录)的操作

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

复制文件夹

使用了两种方式:

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

实现代码和释意如下:


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)
    
    // child_process.spawn('cp', ['-r', copiedPath, resultPath])

    
    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()) {
 
 const readStream = fs.createReadStream(ccp)
 const writeStream = fs.createWriteStream(crp)
 readStream.pipe(writeStream)
      } else {
 try {
   
   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)
   }
 }
 
 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

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


const type = process.argv[2]

function execute() {
  
  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()

命令行传参数


process.argv.forEach((val, index) => {
  console.log(`${index}: ${val}`);
});

利用 fs-extra 实现

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



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…

总结

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/74330.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号