node.js删除文件

如何删除文件node.js?

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

我没有看到删除命令?

751345 次浏览

我认为你想使用fs.unlink

有关fs的更多信息,请参阅这里

您可以调用fs.unlink(path, callback)进行异步解除关联(2)或fs.unlinkSync(path)进行同步解除关联(2)。 其中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.statfs.stat同步同步)而不是fs.exists。因为根据最新的node.js留档fs.exists现在已弃用

例如:-

 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.unlink删除文件。

但根据Node.js留档

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

要检查文件是否存在而不进行事后操作,建议使用fs.access()

要检查文件是否可以删除,请改用fs.access

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-额外,它为您提供fs中的所有内容,加上所有内容都是Promisify。作为奖励,有一个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(路径,回调)函数。这是一个带有“错误返回”模式的函数包装器示例:

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

从文件名与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和Node 10+就在这里。下面的版本使用甜蜜的异步/等待方式。

现在无需将fs.unlink包装到Promises中,也无需再使用其他包(如fs-extra)。

只需使用原生fs Promisesapi

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.unlink规范来自Node文档。

另外请注意,fs.promisesAPI在Node 10. x. 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.

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

建议在删除之前使用访问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

您可以使用下面的代码。我认为它有效。

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

异步删除文件或符号链接。除了可能的异常之外,不会为完成回调提供任何参数。

fs.unlink()在目录上不起作用,无论是否为空。要删除目录,请使用fs.rmdir()。

更多细节