2023-05-22 05:00:06

Node.js删除文件

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

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

我没有看到删除命令?


当前回答

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

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.unlinkSync()如果你想同步删除文件 Fs.unlink()如果你想异步删除它。

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

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

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

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

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

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