希望获得一些帮助。 我想删除文件名称为“ 人”的文件,在Codeigniter中,我可以使用以下代码:
$this->load->helper('directory');
$map = directory_map('./_cache/', FALSE, TRUE);
$cb = array();
foreach($map as $file){
if (strpos($file, $_post['fname']) !== false) {
unlink($file);
$cb[$file] = "deleted";
}
}
return $cb;
成功试用的结果仅删除一个文件,代码如下:
this.remove = function (fname, callback) {
const filesname = secret.pathCache + fname;
fs.unlink(filesname, (err) => {
if (err)
throw err;
callback("Removed : " + filesname);
});
}
也许有人可以帮助我,提供有关如何删除多个同名文件的信息,只执行一次,谢谢。
完整代码:
var fs = require('fs');
const secret = require("../Secret");
function Cache() {
this.add = function (fname, contents) {
const filesname = secret.pathCache + fname;
const resjson = JSON.stringify(contents);
fs.writeFile(filesname, resjson, 'utf8', function (err) {
if (err)
throw err;
});
}
this.view = function (fname, callback) {
const filesname = secret.pathCache + fname;
let rawdata = fs.readFileSync(filesname);
let data = JSON.parse(rawdata);
return callback(data);
}
this.check = function (fname, callback) {
const filesname = secret.pathCache + fname;
fs.exists(filesname, function (exists) {
if (exists) {
res = "cached";
} else {
res = "null";
}
return callback(res);
});
}
this.remove = function (fname, callback) {
const filesname = secret.pathCache + fname;
fs.unlink(filesname, (err) => {
if (err)
throw err;
callback("Removed : " + filesname);
});
}
this.removeAll = function (fname, callback) {
fs.readdir(folder, (err, files) => {
files.forEach(file => {
callback("Removed : " + file);
});
})
}
}
module.exports = new Cache();
答案 0 :(得分:0)
使用readdir获取目录中的文件,然后过滤出匹配的文件并将其删除。
array()
答案 1 :(得分:0)
您可以使用Promise.all
来跟踪文件删除的进度。首先阅读目录并根据fname
this.remove = function (fname, callback) {
fs.readdir(secret.pathCache, (err, files) => {
files = files.filter(file => file.includes(fname));
// you may need to construct path "f" here.
const unlinkPromises = files.map(f => fs.unlink(f))
Promise.all(unlinkPromises).then(callback);
});
}