简体   繁体   English

node.js 删除文件

[英]node.js remove file

How do I delete a file with node.js?如何删除带有 node.js 的文件?

http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback

I don't see a remove command?我没有看到删除命令?

I think you want to usefs.unlink .我想你想使用fs.unlink

More info on fs can be found here .更多关于fs的信息可以在这里找到。

You can call fs.unlink(path, callback) for Asynchronous unlink(2) or fs.unlinkSync(path) for Synchronous unlink(2).您可以为异步 unlink(2) 调用fs.unlink(path, callback)或为同步 unlink(2) 调用 fs.unlinkSync( fs.unlinkSync(path) )。
Where path is file-path which you want to remove.其中path是您要删除的文件路径。

For example we want to remove discovery.docx file from c:/book directory.例如,我们想从c:/book目录中删除discovery.docx文件。 So my file-path is c:/book/discovery.docx .所以我的文件路径是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 .因此,请使用fs.statfs.statSync ( Synchronous ) 而不是fs.exists Because according to the latest node.js documentation , fs.exists now deprecated .因为根据最新的 node.js文档fs.exists现在已弃用

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

I don't think you have to check if file exists or not, fs.unlink will check it for you.我认为您不必检查文件是否存在, fs.unlink会为您检查。

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

2019 and Node 10+ is here . 2019 和 Node 10+ 就在这里 Below the version using sweet async/await way.下面的版本使用sweet async/await方式。

Now no need to wrap fs.unlink into Promises nor to use additional packages (like fs-extra ) anymore.现在无需将fs.unlink包装到 Promises 中,也无需再使用其他包(如fs-extra )。

Just use native fs Promises API .只需使用本机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. 这是来自 Node 文档的fsPromises.unlink规范。

Also please note that fs.promises API marked as experimental in Node 10.xx (but works totally fine, though), and no longer experimental since 11.14.0 .另请注意,fs.promises API 在 Node 10.xx 中标记为实验性的(但工作完全正常),并且自11.14.0起不再是实验性的。

2020 Answer 2020答案

With the release of node v14.14.0 you can now do.随着 node v14.14.0的发布,您现在可以这样做了。

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

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

As the accepted answer, use fs.unlink to delete files.作为接受的答案,使用fs.unlink删除文件。

But according to Node.js documentation但根据Node.js 文档

Using fs.stat() to check for the existence of a file before calling fs.open() , fs.readFile() or fs.writeFile() is not recommended.不建议在调用fs.open()fs.readFile()fs.writeFile()之前使用fs.stat()检查文件是否存在。 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.要检查文件是否存在而不随后对其进行操作,建议使用fs.access()

to check files can be deleted or not, Use fs.access instead检查文件是否可以删除,使用fs.access代替

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

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

Simple and sync简单和同步

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

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');
    })
}
  • fs.unlinkSync() if you want to remove files synchronously and fs.unlinkSync()如果你想同步删除文件并且
  • fs.unlink() if you want to remove it asynchronously. fs.unlink()如果你想异步删除它。

Here you can find a good article.在这里你可以找到一篇好文章。

Just rm -rf it只需rm -rf

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 .使用require("fs").rmSyncrequire("fs").rm

you can use del module to remove one or more files in the current directory.您可以使用del模块删除当前目录中的一个或多个文件。 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.您可以使用fs.unlink(path, callback)函数。 Here is an example of the function wrapper with "error-back" pattern:下面是一个带有“error-back”模式的函数包装器示例:

 // 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仅使用 fs.unlink - 删除文件, fs.readdir - 从目录中获取所有文件

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]) 
        }
    }
});

It's very easy with fs.使用 fs 非常容易。

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

2022 Answer 2022答案

Never do any sync operation in Nodejs永远不要在 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参考: https ://nodejs.org/api/fs.html#promise-example

It is recommended to check file exists before deleting using access or stat建议在使用accessstat删除之前检查文件是否存在

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参考: https ://nodejs.org/api/fs.html#fsaccesspath-mode-callback

fs-extra provides a remove method: fs-extra提供了一个 remove 方法:

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 https://github.com/jprichardson/node-fs-extra/blob/master/docs/remove.md

You can use the below code.您可以使用以下代码。 I think it works.我认为它有效。

const fs = require('fs');
fs.unlink('./uploads/file.png', function (err) {            
    if (err) {                                                 
        console.error(err);
        console.log('File not found');                                    
    }else{
        console.log('File Delete Successfuly');      
    }                                                                      
});

Use NPM module fs-extra , which gives you everything in fs, plus everything is Promisified.使用NPM 模块 fs-extra ,它为您提供 fs 中的所有内容,并且所有内容都是 Promisified。 As a bonus, there's a fs.remove() method available.作为奖励,有一个fs.remove() 方法可用。

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

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

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