node文件系统常见操作

创建文件夹

const createFolder = function (p) {
 const arr = p.split('/')
 const dirCache = {}
 let dir = arr[0]
 for (let i = 0; i < arr.length; i++) {
   if (!dirCache[dir] && !fs.existsSync(dir)) {
     dirCache[dir] = true
     fs.existsSync(dir)
   }
   dir = dir + '/' + arr[i]
 }
 fs.writeFileSync(p, '')
}

删除文件夹

const delFolder = function (filePath) {
  const files = []
  if (fs.existsSync(filePath)) {
    const files = fs.readdirSync(filePath)
    files.forEach((file) => {
      const nextFilePath = `${filePath}/${file}`
      const states = fs.statSync(nextFilePath)
      if (states.isDirectory()) {
        delFolder(nextFilePath)
      } else {
        fs.unlinkSync(nextFilePath)
      }
    })
    fs.rmdirSync(filePath)
  }
}

删除文件

// 删除文件
function delFile(path) {
  return new Promise((resolve, reject) => {
    fs.unlink(path, err => {
      if (err) {
        resolve()
      } else {
        resolve()
      }
    })
  })
}

复制文件夹

const copyFile = async function (srcPath, tarPath) {
  try {
    console.log(srcPath, tarPath)
    // createFolder(tarPath)
    return fs.writeFileSync(tarPath, fs.readFileSync(srcPath))
  } catch (err) {
    console.log(err)
  }
}

文件是否存在

const checkFolderExist = function (p) {
  try {
    const res = fs.statSync(p)
    return res.isDirectory()
  } catch (e) {
    return false
  }
}

写入json配置到本地文件

function json2File(json, path) {
  return new Promise((resolve, reject) => {
    let jsonStr = JSON.stringify(json, null, 2);
    fs.writeFile(path, jsonStr, (err) => {
      if (err) {
        reject(err)
      } else {
        resolve()
      }
    });
  })
}

你可能感兴趣的:(前端开发,前端,javascript,开发语言)