Home > Blockchain >  NestJS & fs writeFile not working as expected
NestJS & fs writeFile not working as expected

Time:01-13

So, when i try to upload a file via NestJS FS and Socket.io with Angular, it gives an error:

Error: EISDIR: illegal operation on a directory, open 'CDN/attachments/63aea8c5e37c6b1242a6973f/63aea86fe37c6b1242a6970a/20230112140045/'
    at Object.openSync (node:fs:584:3)
    at writeFileSync (node:fs:2201:35)
    at C:\Users\alms\Desktop\Chatenium2\chatenium-server\src\chat\message\dm\dm.service.ts:87:26
    at Array.forEach (<anonymous>)
    at Socket.<anonymous> (C:\Users\alms\Desktop\Chatenium2\chatenium-server\src\chat\message\dm\dm.service.ts:74:20)
    at Socket.emit (node:events:513:28)
    at Socket.emitUntyped (C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\socket.io\dist\typed-events.js:69:22)
    at C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\socket.io\dist\socket.js:614:39
    at processTicksAndRejections (node:internal/process/task_queues:77:11)

Can you tell me why? Thanks

Heres my code:

Angular (FrontEnd):


      if (ok == true || this.draftImages.length !== 0) {

        let files: any = []

          let dateX = cur_day   hours   minutes   seconds;

          this.draftImages.forEach((file: any) => {
            files.push(file.file)
          })

            this.dmService.sendMessage({
              message: message,
              chatid: this.chatid,
              userid: this.userData.userid,
              username: this.userData.username,
              pfp: this.userData.pfp,
              files: files,
              filesDest: `${this.chatid}/${this.userData.userid}/${dateX}/`
            });

  }

NestJS (BackEnd ("data" is a data coming from the socket.on function)):

        data.files.forEach(file => {

          console.log("FILE:" file)

          function mkdirRecursiveSync(path: string) {
            if (!existsSync(path)) {
              mkdirRecursiveSync(dirname(path));
              mkdirSync(path);
            } 
          } 

          mkdirRecursiveSync(`CDN/attachments/${data.filesDest}`)

            writeFileSync(`CDN/attachments/${data.filesDest}`, file)
        });  
            

CodePudding user response:

The error is thrown because you're trying to write to a directory instead of a file. You need to specify a file name so node.js can write.

If CDN/attachments/63aea8c5e37c6b1242a6973f/63aea86fe37c6b1242a6970a/20230112140045/ is a path to file, then you should remove / from the end of the path. Otherwise, if this is not a path to a file, and it's a directory path, then you need to specify a name for the file, like this:

writeFileSync(`CDN/attachments/${data.filesDest}/${someFileName}`, file)

fs.writeFileSync( file, data, options )

more about writeFileSync

  • Related