Skip to content

Instantly share code, notes, and snippets.

@beevelop
Created July 1, 2015 13:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save beevelop/e2b3e66085ed3e53aebc to your computer and use it in GitHub Desktop.
Save beevelop/e2b3e66085ed3e53aebc to your computer and use it in GitHub Desktop.
Get the most recently changed file in NodeJS
var path = require('path');
var fs = require('fs');
var getMostRecent = function (dir, cb) {
var dir = path.resolve(dir);
var files = fs.readdir(dir, function (err, files) {
var sorted = files.map(function(v) {
var filepath = path.resolve(dir, v);
return {
name:v,
time:fs.statSync(filepath).mtime.getTime()
};
})
.sort(function(a, b) { return b.time - a.time; })
.map(function(v) { return v.name; });
if (sorted.length > 0) {
cb(null, sorted[0]);
} else {
cb('Y U NO have files in this dir?');
}
})
}
getMostRecent('./', function (err, recent) {
if (err) console.error(err);
console.log(recent);
});
@lucamarogna
Copy link

With Promise:

const path	= require('path');
const fs	= require('fs');
function getMostRecent(dir) {
	return new Promise((resolve, reject) => {
		dir = path.resolve(dir);
		fs.readdir(dir, (err, files) => {
			const sorted = files.map((v) => {
				const filepath = path.resolve(dir, v);
				return {
					name:v,
					time:fs.statSync(filepath).mtime.getTime()
				};
			})
				.sort((a, b) => b.time - a.time)
				.map(v => v.name);

			if (sorted.length > 0) {
				resolve(sorted[0]);
			} else {
				reject('Y U NO have files in this dir?');
			}
		});
	});
}

@beevelop
Copy link
Author

beevelop commented May 4, 2021

With the recent versions of Node.js you could also make use of fsPromises: https://nodejs.org/api/fs.html#fs_fspromises_readdir_path_options

No need to wrap it on your own anymore 🎉 🍻

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment