简体   繁体   中英

How to delete a file in sailsjs?

I've been working on a project where I need to regularly update the associations and database. I'm stuck with the deletion of files. I used fs.unlink of fs for this purpose, but it throws some error.

Code snippet -

fs.unlinkSync("/images/uploadedImages/70c9c2c4-74de-41c1-b096-c403b749a1a9.png");
sails.log.info("Logo deleted succesfully");

Error log -

fs.js:932
return binding.unlink(pathModule._makeLong(path));
Error: ENOENT: no such file or directory, unlink '/images/uploadedImages/70c9c2c4-74de-41c1-b096-c403b749a1a9.png'

Also the file 70c9c2c4-74de-41c1-b096-c403b749a1a9.png exists in the path /images/uploadedImages/, which is inside the assets folder of sailsjs structure.

Isn't there any way to achieve this?

it seems file which you passed to fs.unlinkSync() doesn't exist make sure you have this file

/images/uploadedImages/70c9c2c4-74de-41c1-b096-c403b749a1a9.png

then it will work .

Figured out the issue. Sailsjs framework doesn't start searching for path inside the assets folder by it's own.

Changing the path from - /images/uploadedImages/70c9c2c4-74de-41c1-b096-c403b749a1a9.png to ./assets/images/uploadedImages/70c9c2c4-74de-41c1-b096-c403b749a1a9.png solves the problem.

If any one still finding the answer, below can be the good approach if you want to do some operation on file.

with fs.access you can check whether file is available or not before you do any operation on file. One can use fs.accessSync also for Synchronous behaviour.

In below example, i have used fs.unlink but one can also use fs.unlinkSync for deletion of file.

 // import in file const fs = require('fs') // path of your file let path = 'path to your file' // fs.access will check if file is available or not fs.access(path, fs.F_OK, (err) => { if (err) { console.error(err) return } //file exists, Go for delete operation fs.unlink(path , function (err) { if (err) { console.error(err); return } console.log('Image File has been Deleted'); }); })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM