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.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-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

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

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

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

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

你可以调用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);