Refactor fileOps.getNewestFile

Simplify getNewestFile by converting it to an async function, use the
fs-extra promise based fs functions and remove the files argument as
well as the callback.

Refactors the tests as well to use the test/temp folder.
This commit is contained in:
Hornwitser committed 2019-10-14 15:51:45 +02:00
1 parent 6a870be233
commit cbcf868c9e
3 files changed
+62 -112

No files matched your search

+21 -37
View File
@@ -1,44 +1,28 @@
const fs = require("fs");
const fs = require("fs-extra");
const path = require("path");
// gets newest file in a directory
// dir is directory
// files is array of filenames
// callback(err, filename string);
var getNewestFile = function(dir, files, callback) {
if (!callback) throw new Error("Missing callback");
if (!files || (files && files.length === 0)) {
callback(new Error("No files"));
return;
}
// we are appending the file name to the directory, without the
// "/" we would get paths like /folderfile.txt instead of /folder/file.txt
if(dir[dir.length-1] != "/"){
dir += "/";
}
var newest = { file: files[0] };
var checked = 0;
fs.stat(dir + newest.file, function(err, stats) {
if(err) {
callback(err);
} else {
newest.mtime = stats.mtime;
for (var i = 0; i < files.length; i++) {
var file = files[i];
(function(file) {
fs.stat(file, function(err, stats) {
++checked;
if (stats.mtime.getTime() > newest.mtime.getTime()) {
newest = { file : file, mtime : stats.mtime };
}
if (checked == files.length) {
callback(undefined,newest);
}
});
})(dir + file);
/**
* Returns the newest file in a directory
*
* @param {string} directory - The directory to look for the newest file in.
* @returns {string|null}
* Name of the file with the newest timestamp or null if the
* directory contains no files.
*/
async function getNewestFile(directory) {
let newestTime = new Date(0);
let newestFile = null;
for (let entry of await fs.readdir(directory, { withFileTypes: true })) {
if (entry.isFile()) {
let stat = await fs.stat(path.join(directory, entry.name));
if (stat.mtime > newestTime) {
newestTime = stat.mtime;
newestFile = entry.name;
}
}
});
}
return newestFile;
}
// get names of all directories in directory