How can I find the oldest folder in a node directory? - node.js

I am trying to find the oldest folder in a directory of my nodejs app.
Right now I get the folder names by fs.readdirSync and the I try to run through the mtime in a for-loop with the fs.stat function. But it does not return any values.
cron.schedule('* * * * *', () => {
folders = fs.readdirSync(__dirname + '/uploads/');
var oldestTime;
var oldest;
for (var i = 0; i < folders.length; i++) {
let stats = fs.statSync(folders[i]);
if (oldestTime == undefined || stats.mtime < oldestTime) {
oldestTime = stats.mtime;
oldest = folders[i];
}
}
console.log("oldest folder name is:", oldest)
}
Is there a better way?
Thank you so much!

You use the asynchronous version of fs.stat(). Try the synchronous (callback-free) fs.statSync() instead.
And don't forget that readdir returns results named . for the current directory and .. for the parent directory. You may want to exclude those from your mtime search.
And please spend some time reading up on the Javascript asynchronous programming model.

folders = fs.readdirSync(__dirname + "/uploads");
var oldestTime;
var oldest;
for (var i = 0; i < folders.length; i++) {
let stats = fs.statSync(__dirname + "/uploads/" + folders[i]);
if (oldestTime == undefined || stats.mtime < oldestTime) {
oldestTime = stats.mtime;
oldest = folders[i];
}
}
console.log("oldest folder name is:", oldest)
or use sort to get the oldest one:
const fs = require('fs');
const cron = require("cron");
var job = new cron.CronJob('* * * * * *', function () {
const folders = fs.readdirSync(__dirname + "/uploads");
var oldest = folders.sort((a, b) => fs.statSync(__dirname + '/uploads/' + a).mtime - fs.statSync(__dirname + '/uploads/' + b).mtime)[0];
console.log("oldest folder name is:", oldest)
});
job.start();

Related

Change order of items (shuffle) in .txt file NodeJS

How can I change order of items that are in .txt file in NodeJS using fs?
The items are one item = one line in .txt file.
I want to randomize/shuffle it and write shuffled version to the .txt file.
For a file with content as follows
first line
second
...
you can try something like this:
const fs = require('fs');
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const array = fs.readFileSync('file.txt').toString().split("\n");
fs.writeFileSync('file.txt', shuffleArray(array).join('\n'));

Load random file from directory

So i'm building a game and i want to choose a random file from a directory as a map. I found this old topic which gave the answer
const randomFile = require('random-file')
const dir = '/tmp/whatever'
randomFile(dir, (err, file) => {
console.log(`The random file is: ${file}.`)
})
but it seems that fs is no longer in use, but fs.realpath
Its pretty simple:
const fs = require("fs");
const path = require("path");
fs.readdir(path.join(process.cwd(), "maps"), (err, files) => {
console.log(err, files)
let max = files.length - 1;
let min = 0;
let index = Math.round(Math.random() * (max - min) + min);
let file = files[index];
console.log("Random file is", file);
});
In less then 20 lines.
Why do people use for every simple task a external module?!
Regardless that the package does not what you want...

Node js fs.exists only searching file in current directory

I have setup process.env.path variables and fs.exists(fileName). Node is not able to find the file if it is not in its currently directory.
Is there someway i can configure node to search for file in all directory mentioned in 'process.env.path'.
This isn't supported out of the box. You will have to find a suitable npm package that already does this for you or write your own code. Something along the lines of the code that is in node-whereis:
var fs = require('fs');
function whereIsMyFile(filename){
var pathSep = process.platform === 'win32' ? ';' : ':';
var directories = process.env.PATH.split(pathSep);
for (var i = 0; i < directories.length; i++) {
var path = directories[i] + '/' + filename;
if (fs.existsSync(path)) {
return path;
}
}
return null;
}

Get latest files inside a folder

i have a folder stucture like
var/
testfolder1/
myfile.rb
data.rb
testfolder2/
home.rb
sub.rb
sample.rb
rute.rb
inside var folder contains subfolders(testfolder1,testfolder2) and some files(sample.rb,rute.rb)
in the following code returing a josn object that contains folders and files inside the var folder
like
{
'0': ['sample.rb', 'rute.rb'],
testfolder1: ['myfile.rb',
'data.rb',
],
testfolder2: ['home.rb',
'sub.rb',
]
}
code
var scriptsWithGroup = {};
fs.readdir('/home/var/', function(err, subfolder) {
if(err) return context.sendJson({}, 200);
var scripts = [];
for (var j = 0; j < subfolder.length; j++) {
var scriptsInFolder = [];
if(fs.lstatSync(scriptPath + subfolder[j]).isDirectory()) {
fs.readdirSync(scriptPath + subfolder[j]).forEach(function(file) {
if (file.substr(file.length - 3) == '.rb')
scriptsInFolder.push(file);
});
scriptsWithGroup[subfolder[j]] = scriptsInFolder;
} else {
if (subfolder[j].substr(subfolder[j].length - 3) == '.rb')
scripts.push(subfolder[j]);
}
}
scriptsWithGroup["0"] = scripts;
console.log(scriptsWithGroup)
context.sendJson(scriptsWithGroup, 200);
});
What i need is i want to return the latest modified or created files.here i only use 2 files inside folders it contains lots of files.so i want to return latest created ones
I'm going to assume here that you want only the most recent two files. If you actually want them all, just sorted, just remove the slice portion of this:
scriptsInFolder = scriptsInFolder.sort(function(a, b) {
// or mtime, if you're only wanting file changes and not file attribute changes
var time1 = fs.statSync(a).ctime;
var time2 = fs.statSync(b).ctime;
if (time1 < time2) return -1;
if (time1 > time2) return 1;
return 0;
}).slice(0, 2);
I'll add, however, that it's typically considered best practice not to use to the synchronize fs methods (e.g. fs.statSync). If you're able to install async, that would be a good alternative approach.
const fs = require('fs');
const path = require('path');
const getMostRecentFile = (dir) => {
const files = orderReccentFiles(dir);
return files.length ? files[0] : undefined;
};
const orderReccentFiles = (dir) => {
return fs.readdirSync(dir)
.filter(file => fs.lstatSync(path.join(dir, file)).isFile())
.map(file => ({ file, mtime: fs.lstatSync(path.join(dir, file)).mtime }))
.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
};
const dirPath = '<PATH>';
console.log(getMostRecentFile(dirPath));

Cannot find module when attempting to automatically import node.js modules

I have a directory tmp that has 3 test node.js modules [mod0.js, mod1.js, mod2.js].
I am attempting to write a function in order to import these three modules into an array and then return said array. I can drop to REPL and can import each file using var x = require("./tmp/mod0"); etc without any issue.
When I attempt to run the following function though to automate this, I receive the error [Error: Cannot fine module './tmp/mod0'].
var _importFiles = function(path, files){
var moduleList = []
, trimmedName;
files.forEach(function (element, index, array){
if (_fs.lstatSync(path + "/" + element).isFile()){
trimmedName = element.substring(0, (element.length - 3));
moduleList.push(require("./" + path + "/" + trimmedName));
}
});
return moduleList;
};
I am passing in 'tmp' for the path parameter and the output of fs.readdirSync(path) for the files parameter.
If I check process.cwd(); within the if block, it matches that of the REPL console.
I'm trying to figure out why it works when I manually do it in REPL but not automated.
I modified the code slightly to this:
var _fs = require('fs');
var path = process.cwd() + '/tmp'
var _importFiles = function(path, files){
var moduleList = [], trimmedName;
files.forEach(function (element, index, array){
if (_fs.lstatSync(path + "/" + element).isFile()){
trimmedName = element.substring(0, (element.length - 3));
moduleList.push(require("./" + path + "/" + trimmedName));
}
});
return moduleList;
};
var imports = _importFiles('./tmp', _fs.readdirSync(path));
console.log(imports);
Which gives me:
$ node import.js
[ 'imported mod0 automatically', 'imported mod1 automatically' ]
The mod files are simple module.exports = "imported mod(x) automatically";
So now my return list has an array. Also; Make sure your directory has read permissions (which im sure it does)

Resources