我如何删除一个文件与node.js?
http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback
我没有看到删除命令?
我如何删除一个文件与node.js?
http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_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。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.'));
}
});
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。
作为公认的答案,使用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');
});