How do I delete a file with node.js?
http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback
I don't see a remove command?
How do I delete a file with node.js?
http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback
I don't see a remove command?
delete alias!rmFile aliasrm alias if they have rmdir methodsfs.unlinkSync()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); 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'); }); }); 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.fs.unlink perform when file not existed, so my view is that check file before remove.2020 Answer
With the release of node v14.14.0 you can now do.
fs.rmSync("path/to/file", { force: true, }); force <boolean> When true, exceptions will be ignored if path does not exist. Default: false.var fs = require('fs'); to the beginning.fs/promises and await fs.rm(resultsFile, { force: true }) is probably better, to avoid the sync call.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`); } }); 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.')); } }); fs.exists and before you remove it with fs.unlink? It could happen.unlink, and if it doesn't exist, handle the ENOENT error. Otherwise you can create a race condition.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.
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().
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 callingfs.open(),fs.readFile()orfs.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'); }); 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.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'); }); 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
unlink is a promise. Best practice would be to use promise like ".then .catch".then .catch syntax.fs.unlinkSync() if you want to remove files synchronously andfs.unlink() if you want to remove it asynchronously.Here you can find a good article.
Here's the most minified code I found which doesn't cause errors:
fs.rm(filePath,()=>{}) Unfortunately, the callback '()=>{}' is necessary to avoid errors, which I think is stupid, but whatever, it works!
fs.rm(filePath,_=>{})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) 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')); }); 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'); } }) }; 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]) } } }); fs-extra provides a remove method:
const fs = require('fs-extra') fs.remove('/tmp/myfile') .then(() => { console.log('success!') }) .catch(err => { console.error(err) }) https://github.com/jprichardson/node-fs-extra/blob/master/docs/remove.md
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); Use NPM module fs-extra, which gives you everything in fs, plus everything is Promisified. As a bonus, there's a fs.remove() method available.
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.
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); } 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. 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 } 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); }); you can remove a file using unlinkSync run this code in your code editor
const fs = require('fs'); fs.unlinkSync('filenaem.js') 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, ...