2023-05-22 05:00:06

Node.js删除文件

我如何删除一个文件与node.js?

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

我没有看到删除命令?


我认为你应该使用fs。unlink。

更多关于fs的信息可以在这里找到。


你可以调用fs。unlink(path, callback)用于异步断开(2)或fs.unlinkSync(path)用于同步断开(2)。 path是你要删除的file-path。

例如,我们想从c:/book目录中删除discovery.docx文件。我的文件路径是c:/book/discovery。docx。删除文件的代码是,

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

这是我为此制作的一个小片段,

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。Stat或fs。statSync (Synchronous)而不是fs.exists。因为根据最新的node.js文档,fs。现在已弃用。

例如:-

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

这里的代码,你可以从文件夹中删除文件/图像。

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

我认为你不需要检查文件是否存在,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`);
    }
});

作为公认的答案,使用fs。断开链接删除文件。

但根据Node.js文档

不建议在调用fs.open()、fs.readFile()或fs.writeFile()之前使用fs.stat()检查文件是否存在。相反,用户代码应该直接打开/读取/写入文件,并在文件不可用时处理引发的错误。 要检查一个文件是否存在而不进行操作,建议使用fs.access()。

检查文件是否可以删除,使用fs。访问相反

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

您可以使用del模块删除当前目录中的一个或多个文件。它的好处是可以保护您不删除当前工作目录和以上目录。

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

使用NPM模块fs-extra,它提供了fs中的所有内容,加上所有内容都是承诺的。另外,还有一个fs.remove()方法可用。


下面是我的代码,工作正常。

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

你可以使用fs。Unlink (path, callback)函数。下面是一个带有"error-back"模式的函数包装器示例:

/ /依赖性。 Const fs = require('fs'); //删除文件 const deleteFile = (filePath, callback) => { //断开文件链接。 fs。unlink(filePath, (error) => { If(!错误){ 回调(假); }其他{ callback('删除文件错误'); } }) };


从filename匹配regexp的目录中删除文件。只使用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]) 
        }
    }
});

Fs-extra提供了一个删除方法:

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


fs很简单。

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

2019年和节点10+已经到来。下面的版本采用了甜异步/等待的方式。

现在不需要对fs进行换行。不再链接到Promises,也不再使用额外的包(比如fs-extra)。

只需使用本地fs承诺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);
  }
})();

这里是fsPromises。从Node文档中断开规范链接。

另外,请注意fs。在Node 10.x中承诺API标记为实验性。X(但是工作完全正常),并且从11.14.0开始不再是实验性的。


fs.unlinkSync()如果你想同步删除文件 Fs.unlink()如果你想异步删除它。

在这里你可以找到一篇好文章。


简单且同步

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

2020的答案

有了节点v14.14.0的发行版,您现在就可以这样做了。

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

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


rm -rf它

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

要求(fs)。rmSync或require("fs").rm。


你可以做下面的事情

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

异步删除文件或符号链接。除了一个可能的异常外,没有其他参数被提供给完成回调。

Fs.unlink()将不能在空目录或其他目录上工作。要删除一个目录,请使用fs.rmdir()。

更多的细节


2022的答案

不要在Nodejs中做任何同步操作

若要异步删除文件,

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

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

建议在使用access或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'}`);
});

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