node文件操作-读取复制写入文件

224 阅读1分钟

本章内容主要涉及node传参和参数获取、path模块、fs模块部分基础功能使用

1. node传参和参数获取

  • node执行js文件命令如下:

    node .\index.js
    
  • 需要传参直接跟在命令后面即可,多个参数可用空格分开

     node .\index.js files files_new .js .html
    
  • 参数获取 通过process全局对象获取

    process.argv
    

    如下:argv中的第一项是node所在位置路径,第二项是当前执行的js文件所在路径,后面的参数就是自己传入的参数了

    image.png

2. path模块

  • 用于处理路径,path.resolve()将传入的路径片段解析为绝对路径
     console.log(path.resolve('./files'))
     // 输出 D:\private\test\node-practice\fs\files
    

3. fs模块

  • node中的文件系统,提供系统中文件读写增删等操作功能

4. 案例

将一个文件夹下的指定类型的文件复制到一个新文件夹下

 const fs = require('fs')
 const path = require('path')
 const dirName = process.argv[2]
 const copyDirName = process.argv[3]
 const extNames = process.argv.slice(4)

 const dirPath = path.resolve(dirName)
 const copyDirPath = path.resolve(copyDirName)
 fs.mkdirSync(copyDirPath, {recursive: true})

 const files = fs.readdirSync(dirPath)
 files.forEach(item => {
     const extName = path.extname(item)
     if (extNames.includes(extName)) {
         const filePath = path.resolve(dirPath, item)
         const copyFilePath = path.resolve(copyDirPath, item)
         fs.copyFileSync(filePath, copyFilePath)
     }
 })

运行:

 node .\index.js files files_new .js .html

执行结果:

image.png