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

0pizxfdo  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(274)

我正在尝试将节点中的许多文件写入特定文件夹,但在创建文件夹时遇到一些问题:
我有一个 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)
  }
}
xv8emn3q

xv8emn3q1#

使命感 fs.promises.mkdir() 当path是存在的目录时,仅当 recursivefalse . 所以你需要通过考试 {recursive:true} 作为第二种选择

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

相关问题