Multer deleting functionality form the server when deleted from the database [duplicate]

17 hours ago 2
ARTICLE AD BOX

I think you want to use fs.unlink.

More info on fs can be found here.

Thomas Bormans's user avatar

answered Mar 15, 2011 at 16:58

Nick's user avatar

7 Comments

I believe it comes from the POSIX standard. But you'd think they could add a delete alias!

2012-09-13T08:04:01.84Z+00:00

2015-05-19T15:42:28.01Z+00:00

@PixnBits or an rm alias if they have rmdir methods

2015-08-04T16:41:42.773Z+00:00

for Meteor user, you may want to use fs.unlinkSync()

2015-12-19T18:45:00.397Z+00:00

I think you should provide a whole example, links can change.

2016-11-24T15:33:12.187Z+00:00

You can call fs.unlink(path, callback) for Asynchronous unlink(2) or fs.unlinkSync(path) for Synchronous unlink(2).
Where path is file-path which you want to remove.

For example we want to remove discovery.docx file from c:/book directory. So my file-path is c:/book/discovery.docx. So code for removing that file will be,

var fs = require('fs'); var filePath = 'c:/book/discovery.docx'; fs.unlinkSync(filePath);

Gaurav Gandhi's user avatar

Gaurav Gandhi

3,2112 gold badges30 silver badges40 bronze badges

answered Aug 8, 2014 at 2:42

sourcecode's user avatar

If you want to check file before delete whether it exist or not. So, use fs.stat or fs.statSync (Synchronous) instead of fs.exists. Because according to the latest node.js documentation, fs.exists now deprecated.

For example:-

fs.stat('./server/upload/my.csv', function (err, stats) { console.log(stats);//here we got all information of file in stats variable if (err) { return console.error(err); } fs.unlink('./server/upload/my.csv',function(err){ if(err) return console.log(err); console.log('file deleted successfully'); }); });

Community's user avatar

answered Apr 14, 2016 at 6:03

vineet's user avatar

6 Comments

What if I check it exists, but it's blocked by another process - or, I check it exists, and it's fine, but then another process randomly blocks it before I'm able to delete. How can I block straight after checking? then wouldnt I not be able to delete as its blocked

2016-10-11T15:40:09.227Z+00:00

Note that fs.exists() is deprecated, but fs.existsSync() is not.

2017-01-21T16:14:48.45Z+00:00

There's a reason it's deprecated: often times you creates a race condition if you check that a file exists before deleting it. Instead, you should only call fs.unlink, and if the file doesn't exist, you'll have an ENOENT error in the callback. No need to check before trying to unlink.

2017-07-25T05:26:20.753Z+00:00

@ZachB why delete operation fs.unlink perform when file not existed, so my view is that check file before remove.

2017-07-25T06:29:22.463Z+00:00

The big problem with this approach is that it throws errors for non-exceptional cases. Major debugging a real PITA. Node should have taken a different approach, IMO.

2020-03-05T10:16:32.393Z+00:00

2020 Answer

With the release of node v14.14.0 you can now do.

fs.rmSync("path/to/file", { force: true, });

https://nodejs.org/api/fs.html#fsrmsyncpath-options

answered Dec 19, 2020 at 16:10

Blake Plumb's user avatar

3 Comments

The docs say force means: force <boolean> When true, exceptions will be ignored if path does not exist. Default: false.

2022-05-15T18:59:35.847Z+00:00

Jumping to this answer, it's missing some context. Need to add var fs = require('fs'); to the beginning.

2023-03-20T17:46:02.6Z+00:00

Using fs/promises and await fs.rm(resultsFile, { force: true }) is probably better, to avoid the sync call.

2023-11-15T11:15:15.02Z+00:00

I don't think you have to check if file exists or not, fs.unlink will check it for you.

fs.unlink('fileToBeRemoved', function(err) { if(err && err.code == 'ENOENT') { // file doens't exist console.info("File doesn't exist, won't remove it."); } else if (err) { // other errors, e.g. maybe we don't have enough permission console.error("Error occurred while trying to remove file"); } else { console.info(`removed`); } });

answered Feb 20, 2017 at 11:51

Searene's user avatar

1 Comment

how can i get previous Image name in Our Controller?

2017-12-06T04:54:15.887Z+00:00

Here is a small snippet of I made for this purpose,

var fs = require('fs'); var gutil = require('gulp-util'); fs.exists('./www/index.html', function(exists) { if(exists) { //Show in green console.log(gutil.colors.green('File exists. Deleting now ...')); fs.unlink('./www/index.html'); } else { //Show in red console.log(gutil.colors.red('File not found, so not deleting.')); } });

answered Feb 22, 2016 at 12:45

Stranger's user avatar

3 Comments

2016-11-09T17:06:53.597Z+00:00

What if the file gets deleted by others after you check with fs.exists and before you remove it with fs.unlink? It could happen.

2017-02-20T00:42:03.397Z+00:00

You should not check if a file exists before attempting to unlink it. Just call unlink, and if it doesn't exist, handle the ENOENT error. Otherwise you can create a race condition.

2017-07-25T05:28:27.7Z+00:00

2019 and Node 10+ is here. Below the version using sweet async/await way.

Now no need to wrap fs.unlink into Promises nor to use additional packages (like fs-extra) anymore.

Just use native fs Promises API.

const fs = require('fs').promises; (async () => { try { await fs.unlink('~/any/file'); } catch (e) { // file doesn't exist, no permissions, etc.. // full list of possible errors is here // http://man7.org/linux/man-pages/man2/unlink.2.html#ERRORS console.log(e); } })();

Here is fsPromises.unlink spec from Node docs.

Also please note that fs.promises API marked as experimental in Node 10.x.x (but works totally fine, though), and no longer experimental since 11.14.0.

answered Nov 30, 2019 at 14:10

Artyom Pranovich's user avatar

Simple and sync

if (fs.existsSync(pathToFile)) { fs.unlinkSync(pathToFile) }

answered Nov 7, 2020 at 19:22

João Pimentel Ferreira's user avatar

You can do the following thing

const deleteFile = './docs/deleteme.txt' if (fs.existsSync(deleteFile)) { fs.unlink(deleteFile, (err) => { if (err) { console.log(err); } console.log('deleted'); }) }

Asynchronously removes a file or symbolic link. No arguments other than a possible exception are given to the completion callback.

fs.unlink() will not work on a directory, empty or otherwise. To remove a directory, use fs.rmdir().

More details

Antonin GAVREL's user avatar

Antonin GAVREL

11.4k12 gold badges64 silver badges92 bronze badges

answered Apr 24, 2021 at 2:51

Shailesh Patil's user avatar

unlink is now legacy, don't use it.

It's this simple:

require("fs").rmSync(file_or_directory_path_existing_or_not, {recursive: true, force: true}); // Added in Node.js 14.14.0.

with require("fs").rmSync or require("fs").rm.

Fattie's user avatar

Fattie

9,82276 gold badges455 silver badges771 bronze badges

answered Feb 3, 2021 at 5:31

Константин Ван's user avatar

As the accepted answer, use fs.unlink to delete files.

But according to Node.js documentation

Using fs.stat() to check for the existence of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.

To check if a file exists without manipulating it afterwards, fs.access() is recommended.

to check files can be deleted or not, Use fs.access instead

fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => { console.log(err ? 'no access!' : 'can read/write'); });

Community's user avatar

answered Mar 22, 2017 at 1:52

jasperjian's user avatar

3 Comments

This is a good answer, with a Node.js reference. most people will use unlink directly because they know they have rights to delete the file. But fs.access is a good alternative if they need to check before deletion. But I think if they need to check if a file exists without manipulating it afterwards, they should naturally use fs.stat, fs.access has a different purpose in my humble opinion.

2018-04-05T13:46:16.943Z+00:00

the reason why the documentation recommends against checking for existance is because that information can change between your call to fs.stat/fs.access and the actual operation. For example the file could exist when you call fs.access and then be deleted before you call fs.unlink, or the permissions could change between the two calls. Since you have to handle the error codes of fs.unlink in that case anyways there's no point in calling fs.stat or fs.access.

2019-03-19T15:21:27.33Z+00:00

This is not an answer to the question that was being asked, which is specifically about how to remove the file. (As opposed to, how to know whether you have rights to remove it.)

2021-08-09T02:50:45.147Z+00:00

Here below my code which works fine.

const fs = require('fs'); fs.unlink(__dirname+ '/test.txt', function (err) { if (err) { console.error(err); } console.log('File has been Deleted'); });

sizzle's user avatar

sizzle

2,3522 gold badges21 silver badges32 bronze badges

answered Apr 6, 2018 at 5:53

Thavaprakash Swaminathan's user avatar

3 Comments

I like this answer the best because it's the simplest complete and correct answer for those that want to know how run something after the unlink completes and don't care about customizing the error message.

2018-04-15T22:49:53.503Z+00:00

why are you using __dirname? I wonder if we could place a relative path instead of full path?

2019-09-16T10:40:02.027Z+00:00

I'm using Node / Express / Multer to enable file attachments through REST POST calls. How can you expose fs.unlink in the Node / Express framework so that it can process REST DELETE calls? Posts are exposed with an app.post(...) so is something similar needed to expose the delete request? Multer may not be needed for DELETES, but what has me stuck is how to expose a workable DELETE.

2020-07-16T10:15:59.547Z+00:00

2022 Answer

Never do any sync operation in Nodejs

To asynchronously delete a file,

const { unlink } = require('fs/promises'); (async function(path) { try { await unlink(path); console.log(`successfully deleted ${path}`); } catch (error) { console.error('there was an error:', error.message); } })('/tmp/hello');

ref: https://nodejs.org/api/fs.html#promise-example

It is recommended to check file exists before deleting using access or stat

import { access, constants } from 'fs'; const file = 'package.json'; // Check if the file exists in the current directory. access(file, constants.F_OK, (err) => { console.log(`${file} ${err ? 'does not exist' : 'exists'}`); });

ref: https://nodejs.org/api/fs.html#fsaccesspath-mode-callback

answered Mar 13, 2022 at 22:02

shijin's user avatar

5 Comments

No need to "try catch" if unlink is a promise. Best practice would be to use promise like ".then .catch"

2022-06-15T15:29:30.82Z+00:00

@Marco Please provide documentation backing up your claim that using async/await syntax is not a best practice.

2022-08-19T18:49:52.83Z+00:00

@RohnAdams Not talking async/await syntax - that looks fine. Just saying that the try/catch block is redundant and can get messy since a promise gives you the .then .catch syntax.

2022-08-22T11:35:25.407Z+00:00

@Marco can you provide documentation that suggests that using the try/catch syntax with async/await is not best practice?

2022-08-24T15:08:28.02Z+00:00

Thank you @RohnAdams. You got me there. I can't find anything more than Promise chain error handling is the modern way. Please then allow me to restate my comment by changing 'Best practice' to 'Modern'.

2022-08-26T08:46:17.743Z+00:00

fs.unlinkSync() if you want to remove files synchronously and fs.unlink() if you want to remove it asynchronously.

Here you can find a good article.

Benjamin Zach's user avatar

Benjamin Zach

1,6522 gold badges21 silver badges43 bronze badges

answered Sep 18, 2020 at 11:22

Muhamet Smaili's user avatar

Here's the most minified code I found which doesn't cause errors:

Unfortunately, the callback '()=>{}' is necessary to avoid errors, which I think is stupid, but whatever, it works!

answered Sep 27, 2023 at 23:48

Ehud Kirsh's user avatar

2 Comments

if we're talking minified may I offer a one-character saving :¬D fs.rm(filePath,_=>{})

2024-03-07T10:32:29.02Z+00:00

I have thought about that, and I like your line of thinking, and I do use it for arrow functions with a single input, but this creates a new temporary variable unnecessarily, so I wouldn't.

2024-03-08T12:07:38.513Z+00:00

If you want to use the await keyword without throwing if the file does not exist but do not want to use try/catch, you can use this one liner

await unlink('/path/to/file').catch(() => void 0)

answered Dec 16, 2023 at 17:29

drk's user avatar

1 Comment

should be mentioned this is for fs/promises

2024-01-30T10:15:08.64Z+00:00

you can use del module to remove one or more files in the current directory. what's nice about it is that protects you against deleting the current working directory and above.

const del = require('del'); del(['<your pathere here>/*']).then( (paths: any) => { console.log('Deleted files and folders:\n', paths.join('\n')); });

answered Apr 21, 2017 at 7:10

Amazia Gur's user avatar

1 Comment

If you need to delete multiple files, this is a great option! Thank you for the suggestion.

2020-04-11T13:53:15.193Z+00:00

You may use fs.unlink(path, callback) function. Here is an example of the function wrapper with "error-back" pattern:

// Dependencies. const fs = require('fs'); // Delete a file. const deleteFile = (filePath, callback) => { // Unlink the file. fs.unlink(filePath, (error) => { if (!error) { callback(false); } else { callback('Error deleting the file'); } }) };

answered Sep 20, 2018 at 10:56

Oleksii Trekhleb's user avatar

It's very easy with fs.

var fs = require('fs'); try{ var sourceUrls = "/sampleFolder/sampleFile.txt"; fs.unlinkSync(sourceUrls); }catch(err){ console.log(err); }

answered Oct 3, 2019 at 8:45

Susampath's user avatar

Remove files from the directory that matched regexp for filename. Used only fs.unlink - to remove file, fs.readdir - to get all files from a directory

var fs = require('fs'); const path = '/path_to_files/filename.anyextension'; const removeFile = (fileName) => { fs.unlink(`${path}${fileName}`, function(error) { if (error) { throw error; } console.log('Deleted filename', fileName); }) } const reg = /^[a-zA-Z]+_[0-9]+(\s[2-4])+\./ fs.readdir(path, function(err, items) { for (var i=0; i<items.length; i++) { console.log(items[i], ' ', reg.test(items[i])) if (reg.test(items[i])) { console.log(items[i]) removeFile(items[i]) } } });

answered Sep 29, 2018 at 16:57

Xenia Lvova's user avatar

You can remove the file using the below codes:

Import the unlinkSync:

import { unlinkSync } from 'fs';

Can create a method like this:

export const removeFileFromLocation = async (filePath: string) => { const removeRes = await unlinkSync(filePath); return removeRes; }

Use this method as:

const removeRes = await removeFileFromLocation(`${PATH_DOWNLOADED_FILE}/${sourceFileName}`); console.log("removeFileFromLocation:",removeRes);

enter image description here

answered Mar 24, 2023 at 13:10

Shubham Verma's user avatar

Those who trying to find a way to do the same in a module file, you can check out fs-extra.

import fs from 'fs-extra'

This will allow you to use any of the above-quoted methods defined by fs, there are various async actions also supported by it.

answered Jun 26, 2023 at 7:58

geeky01adarsh's user avatar

Promise example

Promise-based operations return a promise that is fulfilled when the asynchronous operation is complete.

import { unlink } from 'node:fs/promises'; try { await unlink('/tmp/hello'); console.log('successfully deleted /tmp/hello'); } catch (error) { console.error('there was an error:', error.message); }

Callback example

The callback form takes a completion callback function as its last argument and invokes the operation asynchronously. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation is completed successfully, then the first argument is null or undefined.

import { unlink } from 'node:fs'; unlink('/tmp/hello', (err) => { if (err) throw err; console.log('successfully deleted /tmp/hello'); }); The callback-based versions of the node:fs module APIs are preferable over the use of the promise APIs when maximal performance (both in terms of execution time and memory allocation) is required.

Synchronous example

The synchronous APIs block the Node.js event loop and further JavaScript execution until the operation is complete. Exceptions are thrown immediately and can be handled using try…catch, or can be allowed to bubble up.

import { unlinkSync } from 'node:fs'; try { unlinkSync('/tmp/hello'); console.log('successfully deleted /tmp/hello'); } catch (err) { // handle the error }

see more

answered Sep 2, 2023 at 11:52

Lelik's user avatar

Here the code where you can delete file/image from folder.

var fs = require('fs'); Gallery.findById({ _id: req.params.id},function(err,data){ if (err) throw err; fs.unlink('public/gallery/'+data.image_name); });

Shubham Verma's user avatar

Shubham Verma

10.2k8 gold badges70 silver badges88 bronze badges

answered Dec 22, 2016 at 9:54

Mahesh singh chouhan's user avatar

1 Comment

Since node 7 the callback argument is no longer optional and will result in a warning. Pass an empty function if you really don't care about it.

2017-07-24T12:14:18.087Z+00:00

you can remove a file using unlinkSync run this code in your code editor

const fs = require('fs'); fs.unlinkSync('filenaem.js')

answered Jun 6, 2024 at 10:46

Parsa Moloodi's user avatar

2 Comments

There are already various answers here that suggest unlinkSync. While it is not necessarily wrong to still add another answer that suggests the usage, you should think about if it really makes sense, e.g. if it has some improvements over the existing answers. Like additional insight, advantage/disadvantages of its usage, ...

2024-06-06T11:05:06.19Z+00:00

unlinkSync is totally useless, it is legacy. it fails if the file does not exist and in other circumstances. Simply use the new command "rm"

2024-08-05T12:34:10.093Z+00:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article