WriteFile dosent work when creating a file using Buffer

100 Views Asked by At

im trying to upload a file using socket.io , when i upload a file socket send it like a buffer in the documentation they just used WriteFile to create the file like this :

 writeFile("/tmp/upload", file, (err) => {
      callback({ message: err ? "failure" : "success" });
    })

this didnt work for me first here is my socket code :

socket.on('sendMessage', async (data) => {
    let conversation = await Conversation.findOne({
      participants: { $all: [data.sender, data.recipient] },
    })

    if (!conversation) {
      conversation = await Conversation.create({
        participants: [data.sender, data.recipient],
        messages: [],
      })
    }
    const messageData = {
      sender: data.sender,
      recipient: data.recipient,
      content: '',
      files: [],
      timestamp: new Date(),
    }
    if (data.content) {
      messageData.content = data.content
    }
    if (data.files) {
      const filePath = `/uploads/${data.sender}`
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9)

      for (const file of data.content) {
        const extension = file.fileName.split('.').pop()
        const fileName = `file-${uniqueSuffix}.${extension}`
        const fileDestination = path.join(filePath, fileName)

        try {
          const fileData = Buffer.from(file.file)
          console.log(fileData)
          if (!fs.existsSync(filePath)) {
            fs.mkdirSync(filePath, { recursive: true })
          }
          fs.writeFile(
            fileDestination,
            fileData,
            {
              encoding: 'binary',
            },
            (err) => {
              console.log(err)
            }
          )
          messageData.files.push(fileDestination)
          const message = await Message.create(messageData)
          conversation.messages.push(message)
          await conversation.save()
          io.to(data.recipient).emit('receiveMessage', message)
        } catch (error) {
          console.log(error)
        }
      }
    }
    try {
      console.log(messageData)
      const message = await Message.create(messageData)
      conversation.messages.push(message)
      await conversation.save()
      io.to(data.recipient).emit('receiveMessage', message)
      io.to(data.sender).emit('messageSentResponse', {
        succes: true,
        message: message,
      })
    } catch (error) {
      io.to(data.sender).emit('messageSentResponse', { succes: false })
    }
  })

i tried using writeFileAsync since it says that it will create the file if it doesn't exists but it didn't work the error occurs in

fs.writeFile(
            fileDestination,
            fileData,
            {
              encoding: 'binary',
            },
            (err) => {
              console.log(err)
            }
          )

it throws this error :

Error: ENOENT: no such file or directory, open '\uploads\64b14bf1c5d7d952c46a0e0a\file-1689378054216-71111589.jpg'
    at Object.openSync (node:fs:599:3)
    at Object.writeFileSync (node:fs:2221:35)
    at Socket.<anonymous> (C:\Users\Zbiba\Desktop\social-media-app\back-end\Sockets\messages.js:52:14)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  errno: -4058,
  syscall: 'open',
  code: 'ENOENT',
  path: '\\uploads\\64b14bf1c5d7d952c46a0e0a\\file-1689378054216-71111589.jpg'
}

the folder \uploads\64b14bf1c5d7d952c46a0e0a\ is created previously so no need to create it with the mkdir i already tried using it but it says the directory already exists

0

There are 0 best solutions below