javascript 在 Node 中,删除超过一个小时的所有文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19167297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:38:35  来源:igfitidea点击:

In Node, delete all files older than an hour?

javascriptnode.js

提问by user1031947

I want to delete any files older than an hour. This is for automatically cleaning up a tmp uploads directory.

我想删除任何超过一个小时的文件。这是为了自动清理 tmp 上传目录。

Here is my code:

这是我的代码:

fs.readdir( dirPath, function( err, files ) {
    if ( err ) return console.log( err );
    files.forEach(function( file ) {
        var filePath = dirPath + file;
        fs.stat( filePath, function( err, stat ) {
            if ( err ) return console.log( err );
            var livesUntil = new Date();
            livesUntil.setHours(livesUntil.getHours() - 1);
            if ( stat.ctime < livesUntil ) {
                fs.unlink( filePath, function( err ) {
                    if ( err ) return console.log( err );
                });
            }
        });
    });
});

However this just deletes everything in the directory, regardless of whether or not it was uploaded over an hour ago.

然而,这只会删除目录中的所有内容,无论它是否在一个小时前上传。

Am I misunderstanding how to check the age of the file in Node?

我是否误解了如何在 Node 中检查文件的年龄?

采纳答案by cbaigorri

I am using rimrafto recursively delete any file/folder that is older than one hour.

我正在使用rimraf递归删除任何超过一小时的文件/文件夹。

According to the docs, you should use getTime()on the ctime Dateobject instance in order to compare.

根据docs,您应该在 ctime Date对象实例上使用getTime()以进行比较。

var uploadsDir = __dirname + '/uploads';

fs.readdir(uploadsDir, function(err, files) {
  files.forEach(function(file, index) {
    fs.stat(path.join(uploadsDir, file), function(err, stat) {
      var endTime, now;
      if (err) {
        return console.error(err);
      }
      now = new Date().getTime();
      endTime = new Date(stat.ctime).getTime() + 3600000;
      if (now > endTime) {
        return rimraf(path.join(uploadsDir, file), function(err) {
          if (err) {
            return console.error(err);
          }
          console.log('successfully deleted');
        });
      }
    });
  });
});

回答by German Attanasio

I've used find-removefor a similar usecase.

我已经将find-remove用于类似的用例。

According to the documentation and what you are trying to do, the code will be:

根据文档和您要执行的操作,代码将是:

var findRemoveSync = require('find-remove');
findRemoveSync(__dirname + '/uploads', {age: {seconds: 3600}});

I'm actually running that every 6 minutes and deleting files older than 1 hour by doing:

我实际上每 6 分钟运行一次,并通过执行以下操作删除超过 1 小时的文件:

setInterval(findRemoveSync.bind(this,__dirname + '/uploads', {age: {seconds: 3600}}), 360000)

See thisexample on how I'm using find-remove to cleanup the /uploadsfolder.

对我如何使用find -删除清理的例子/uploads文件夹。

回答by STLMikey

It looks like you're comparing whatever "stat.ctime" is to the entire Date object.

看起来您正在将“stat.ctime”与整个 Date 对象进行比较。

if ( stat.ctime < livesUntil ) {

Shouldn't it read:

不应该是这样的:

if ( stat.ctime < livesUntil.getHours() ) {

回答by user956584

Simple recursive solution only del all files !dirs run every 5 hours del older files that 1 day

简单的递归解决方案仅删除所有文件!dirs 每 5 小时运行一次删除 1 天的旧文件

const fs = require('fs');
const path = require('path');

setInterval(function() {
    walkDir('./tmpimages/', function(filePath) {
    fs.stat(filePath, function(err, stat) {
    var now = new Date().getTime();
    var endTime = new Date(stat.mtime).getTime() + 86400000; // 1days in miliseconds

    if (err) { return console.error(err); }

    if (now > endTime) {
        //console.log('DEL:', filePath);
      return fs.unlink(filePath, function(err) {
        if (err) return console.error(err);
      });
    }
  })  
});
}, 18000000); // every 5 hours



function walkDir(dir, callback) {
  fs.readdirSync(dir).forEach( f => {
    let dirPath = path.join(dir, f);
    let isDirectory = fs.statSync(dirPath).isDirectory();
    isDirectory ? 
      walkDir(dirPath, callback) : callback(path.join(dir, f));
  });
};

Source of function

函数源