node.jsnestjsnest

Issue with fs.unlink in Nest JS: Cannot read property 'unlink' of undefined


I was encountering an issue while trying to delete a file using the fs module in Node.js. Here's the code snippet I initially used:

 import fs from 'fs';
 .
 .
 .

 @Delete(':fileName')
 async deleteFile(@Param('fileName') fileName: string) {
  await fs.unlink('../../uploads/${fileName}', (err) => {
   if (err) {
    console.error(err);
    return err;
   }
  });
 }

However, this code was not working as expected, and I received the following error:

Cannot read property 'unlink' of undefined.

After some investigation, I discovered the issue was with how I was importing the fs module. I resolved the problem by changing the import statement as follows:

import * as fs from 'fs';

Solution

  • The error I was getting was Cannot read property 'unlink' of undefined. The problem solved when I changed the import from import fs from 'fs'; to import * as fs from 'fs';

    PD: Make sure you use the correct path (machine path) of the archive inside fs.unlink(path, callback).