Nodejs 获取文件夹中最新生成文件的文件名

var fs = require('fs');
var path = require("path");

var pathName = "C:/Users/Administrator/Desktop";
fs.readdir(pathName, function(err, files){
	    var dirs = [];
	    (function iterator(i){
	      	if(i == files.length) {
		        var maxtime = 0;
		        var maxfileName = '';
		        for(var j = 0;j<dirs.length;j++){
		        	var stat = fs.statSync(path.join(pathName,dirs[j]));
					var fileCreateTimeStamp = (new Date(stat.birthtime)).getTime();
					if(fileCreateTimeStamp>maxtime){
						maxtime = fileCreateTimeStamp;
						maxfileName=dirs[j];
					}
		        }
		        console.log('最终文件',maxfileName);
		        console.log('最终文件绝对路径',path.join(pathName,maxfileName));
                return;
	      	}
		    fs.stat(path.join(pathName, files[i]), function(err, data){     
		        if(data.isFile()){               
		            dirs.push(files[i]);
		        }
		        iterator(i+1);
		    });   
	})(0);
});

    原文作者:blackjewel
    原文地址: https://blog.csdn.net/blackjewel/article/details/123606696
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞