简体   繁体   English

如何删除sailsjs中的文件?

[英]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.为此,我使用了fs 的fs.unlink ,但它引发了一些错误。

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.此外,文件 70c9c2c4-74de-41c1-b096-c403b749a1a9.png 存在于路径 /images/uploadedImages/ 中,该路径位于sailsjs 结构的资产文件夹内。

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您传递给fs.unlinkSync()似乎不存在,请确保您拥有此文件

/images/uploadedImages/70c9c2c4-74de-41c1-b096-c403b749a1a9.png /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. Sailsjs 框架不会自行开始在资产文件夹内搜索路径。

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.将路径从 - /images/uploadedImages/70c9c2c4-74de-41c1-b096-c403b749a1a9.png更改为./assets/images/uploadedImages/70c9c2c4-74de-41c1-b096-c403b749a1a9.png问题

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.使用fs.access您可以在对文件进行任何操作之前检查文件是否可用。 One can use fs.accessSync also for Synchronous behaviour.也可以将fs.accessSync用于同步行为。

In below example, i have used fs.unlink but one can also use fs.unlinkSync for deletion of file.在下面的例子中,我使用了fs.unlink但也可以使用fs.unlinkSync来删除文件。

 // 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'); }); })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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