创建文件夹并循环写入多个文件

Create a folder and write multiple files on a loop

我正在尝试将节点中的一些文件写入特定文件夹,但在创建文件夹时遇到一些问题:

我有一个 upload.js 文件从前端接收两个文件,然后我使用异步 for 循环不阻塞事件循环,我有一个函数 运行对于它收到的每个文件,此函数检查文件夹是否存在,如果不存在则创建它:

import Router from 'express'
import multer from 'multer'
import { resolve } from 'path'
import { constants } from 'fs'
import { writeFile, mkdir, access } from 'fs/promises'

async function asyncForEach(array, callback) {
  for (let i = 0, j = array.length; i < j; i++) {
    await callback(array[i], i, array)
  }
}

router.put('/', upload.array('files', 5), async (req, res) => {
  const { files } = req

  const temporalFolder = `./tmp`

  const writeToFolder = async (name, file) => {
    try {
      await access(temporalFolder, constants.R_OK | constants.W_OK)
    } catch (error) {
      await mkdir(temporalFolder)
    } finally {
      await writeFile(resolve(temporalFolder, name), file)
    }
  }

  await asyncForEach(files, async (file) => { 
    const { originalname, buffer } = file
    writeToFolder(originalname, buffer)
  }

  res.end()
})

export default router

如果文件夹已经创建,我没有收到任何错误消息并且工作正常,但是第一次当文件夹不存在时我得到了这个,即使你一切正常:

[Error: EEXIST: file already exists, mkdir './tmp'] {
   errno: -17,
   code: 'EEXIST',
   syscall: 'mkdir',
   path: './tmp'
}

更新:感谢 Rajdeep Debnath 我用这个修复了它:

const writeToFolder = async (name, file) => {
  try {
    await access(temporalFolder, constants.R_OK | constants.W_OK)
  } catch (error) {
    await mkdir(temporalFolder, { recursive: true })
  } finally {
    await writeFile(resolve(temporalFolder, name), file)
  }
}

当 path 是一个存在的目录时调用 fs.promises.mkdir() 仅当 recursivefalse 时才会导致错误。所以你需要传递 {recursive:true} 作为第二个选项

const writeToFolder = async (name, file) => {
  try {
    await mkdir(temporalFolder, {recursive:true})
    await writeFile(resolve(temporalFolder, name), file)
  } catch (error) {